python said : "1, 2, 3, 6, 7, manbo !"

Ben Finney bignose-hates-spam at and-benfinney-does-too.id.au
Wed Jan 21 21:39:35 EST 2004


On Wed, 21 Jan 2004 17:53:19 -0300, - wrote:
> Why 5 does not appear ? (this was the source of a deep bug in a 4000+
> lines networked program...)

Curious:

    >>> a = range(8)
    >>> for b in a:
    ...     if ( b == 4 ):
    ...             a.remove(b)
    ...     print ( b, a )
    ...
    (0, [0, 1, 2, 3, 4, 5, 6, 7])
    (1, [0, 1, 2, 3, 4, 5, 6, 7])
    (2, [0, 1, 2, 3, 4, 5, 6, 7])
    (3, [0, 1, 2, 3, 4, 5, 6, 7])
    (4, [0, 1, 2, 3, 5, 6, 7])
    (6, [0, 1, 2, 3, 5, 6, 7])
    (7, [0, 1, 2, 3, 5, 6, 7])

It seems that, having removed the current item in the list, the index of
the "for" loop hasn't changed.  The next iteration increments that
index, even though the list itself has become shorter.

-- 
 \       "You know I could rent you out as a decoy for duck hunters?"  |
  `\                                                   -- Groucho Marx |
_o__)                                                                  |
Ben Finney <http://bignose.squidly.org/>



More information about the Python-list mailing list