Monday, December 13, 2010

extend list while iterating


>>> a = [1,2]
>>> for n in a:
...    print n, a, [n-1]*n
...    a += [n-1]*n
...
1 [1, 2] [0]
2 [1, 2, 0] [1, 1]
0 [1, 2, 0, 1, 1] []
1 [1, 2, 0, 1, 1] [0]
1 [1, 2, 0, 1, 1, 0] [0]
0 [1, 2, 0, 1, 1, 0, 0] []
0 [1, 2, 0, 1, 1, 0, 0] []
Note that this only works for lists since they have a defined ordering, and so the iterator doesn't "lose its place" if the list is modified.  For sets and dicts, this type of construct will result in "RuntimeError: changed size during iteration."

No comments:

Post a Comment