質問

Can anyone explain to me exactly why this Python script produces this output?

>>> a = range(0,50)  
>>> for x in a:  
...     a.remove(x)  
...   
>>> a  
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21, 23, 25, 27, 29, 31, 33, 35, 37, 39]

This seems strange to me, because the script only removes every second entry. I would think that the loop would iteratively remove all the items in the list.

役に立ちましたか?

解決

What

for x in a:

Really does is that it uses an internal counter, so it will return a[0], a[1], a[2]...

What happens with your code is that removing an item changes the position where the loop index should point, so:

First loop, index == 0, you remove a[0], which is 0. Second loop, index is 1, but now, a is [1..49], and a[1] is 2.

And so on.

他のヒント

>>> a = range(0,50)  
>>> for x in a[:]:
...     a.remove(x)  
...   
>>> a  
[]

Make a copy of the list (a[:]) so you are not modifying it while iterating through it.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top