Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

List "quirk" in python

Tags:

python

list

I was trying out some things with lists in the interactive interpreter and I noticed this:

>>> list = range(1, 11)
>>> for i in list:
...     list.remove(i)
...
>>> list
[2, 4, 6, 8, 10]

Can anyone explain why it left even numbers? This is confusing me right now... Thanks a lot.

like image 534
Bridgo Avatar asked Dec 05 '22 19:12

Bridgo


2 Answers

It isn't safe to modify a list that you are iterating over.

like image 175
ObscureRobot Avatar answered Dec 07 '22 09:12

ObscureRobot


My guess is that the for loop is implemented like the following:

list = range(1, 11)

i = 0
while i < len(list):
    list.remove(list[i])
    i += 1

print(list)

Every time an element is removed, the "next" element slides into its spot, but i gets incremented anyway, skipping 2 elements.

But yes, ObscureRobot is right, it's not really safe to do this (and this is probably undefined behavior).

like image 43
Owen Avatar answered Dec 07 '22 07:12

Owen