#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Sep 2012
    Posts
    66
    Rep Power
    2

    Modifying during an iterative loop


    I know that it is not safe to modify the list during an iterative looping. However no matter how hard I look I cannot find the reasoning behind this could somebody explain it to me?
  2. #2
  3. Contributing User
    Devshed Demi-God (4500 - 4999 posts)

    Join Date
    Aug 2011
    Posts
    4,841
    Rep Power
    480

    try it!


    Code:
    >>> A = list('abcde')
    >>> for (i, a,) in enumerate(A):
    ...     print(i, a)
    ...     del A[i]
    ... 
    (0, 'a')
    (1, 'c')
    (2, 'e')
    >>> A
    ['b', 'd']
    >>> A = list('abcde')
    >>> for (i, a,) in enumerate(A):
    ...     print(i, a)
    ...     A[:0] = [0]
    ... 
    (0, 'a')
    (1, 'a')
    (2, 'a')
    (3, 'a')
      ...
    (52120, 'a')
    (52121, 'a')
    Traceback (most recent call last):
      File "<stdin>", line 3, in <module>
    KeyboardInterrupt
    >>>
    [code]Code tags[/code] are essential for python code and Makefiles!

IMN logo majestic logo threadwatch logo seochat tools logo