???? i can`t understand it

Robin Munn rmunn at pobox.com
Tue Aug 12 19:09:25 CEST 2003


Smille Purusa <Smille at mail.com> wrote:
> Enrique wrote:
> 
>>>>> a=[1,2,3,4,5]
>>>>> for b in a:
>> ...  a.remove(b)
>> ...
>>>>> a
>> [2, 4]
>>>>>
> Very interesting result but reasonable. If the underlying interpreter uses
> a reference or pointer for the job like this:
> 
> # psudo codes for python
> for(ptr = a.first(); ptr.is_valid(); ++ptr)
> {
>      update('b', value(ptr))
>      call_method('a', 'remove', get_alue('b'))
> }
> 
> ptr may be just an index. So at the first iteration, the first element, '1',
> is removed from a. The next time ptr=1, but a has been changed to [2,3,4,5],
> so '3' is removed, and so on,

This is exactly correct. From the Python reference manual, describing
for loops:

    Warning: There is a subtlety when the sequence is being modified by
    the loop (this can only occur for mutable sequences, i.e. lists). An
    internal counter is used to keep track of which item is used next,
    and this is incremented on each iteration. When this counter has
    reached the length of the sequence the loop terminates. This means
    that if the suite deletes the current (or a previous) item from the
    sequence, the next item will be skipped (since it gets the index of
    the current item which has already been treated). Likewise, if the
    suite inserts an item in the sequence before the current item, the
    current item will be treated again the next time through the loop.
    This can lead to nasty bugs that can be avoided by making a
    temporary copy using a slice of the whole sequence, e.g.,

        for x in a[:]:
            if x < 0: a.remove(x)

You can read the whole thing at:
    http://www.python.org/doc/current/ref/for.html

-- 
Robin Munn <rmunn at pobox.com> | http://www.rmunn.com/ | PGP key 0x6AFB6838
-----------------------------+-----------------------+----------------------
"Remember, when it comes to commercial TV, the program is not the product.
YOU are the product, and the advertiser is the customer." - Mark W. Schumann




More information about the Python-list mailing list