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."

1 comment:

  1. The King Casino | Ventureberg
    Discover the casinosites.one rise and fall of the king casino, one of the 메이피로출장마사지 world's largest The Casino is operated https://vannienailor4166blog.blogspot.com/ by the King Casino titanium earrings Group. ventureberg.com/ You can

    ReplyDelete