???? i can`t understand it

D

David C. Fox

Enrique said:
a=[1,2,3,4,5]
for b in a:
... a.remove(b)
...

As others have noted, modifying a sequence can have strange effects on
iterators.

Presumably, the example above is simplified (since if you really wanted
to remove all elements in a, you would just say a = []). If you want to
selectively remove elements in a, you should have a look at the built-in
function filter. For example, to remove elements < 0:

a = [1,5,7, -4, 2, -10]
a = filter(lambda x: x >= 0, a)

David
 
S

Smille Purusa

Enrique said:
a=[1,2,3,4,5]
for b in a:
... a.remove(b)
...
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,


Smille
 
R

Robin Munn

Smille Purusa said:
Enrique said:
a=[1,2,3,4,5]
for b in a:
... a.remove(b)
...
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,733
Messages
2,569,439
Members
44,829
Latest member
PIXThurman

Latest Threads

Top