List problem

Steven Bethard steven.bethard at gmail.com
Fri Oct 29 19:52:03 CEST 2004


Thomas M. <thomas.sunshine <at> web.de> writes:
> 
> test_list = [1, 2, 3]
> 
> for i in test_list:
>    print i
> 
>    if 1 in test_list:
>       test_list.remove(1)
> 
> Why is the second item not print ?

Maybe this will help illustrate the problem:

>>> test_list = [1, 2, 3]
>>> for i, item in enumerate(test_list):
... 	print item
... 	print "start", i, test_list[i], test_list
... 	if 1 in test_list:
... 		test_list.remove(1)
... 	print "end", i, test_list[i], test_list
... 
1
start 0 1 [1, 2, 3]
end 0 2 [2, 3]
3
start 1 3 [2, 3]
end 1 3 [2, 3]

On the first iteration of the loop, you are looking at item 0 in a 3-item list,
[1, 2, 3].  When you remove 1 from the list, you convert the 3-item list into a
2-item list, thust shifting the indices down, so that test_list[0] is now 2. 
When the for loop continues, it is now looking at index 1, and the item at index
1 in your (adjusted) 2-item list is 3.

In general, removing elements from a list while you're iterating though the list
is a bad idea.  Perhaps a better solution is a list comprehension:

>>> test_list = [1, 2, 3]
>>> [x for x in test_list if x != 1]
[2, 3]
>>> for item in [x for x in test_list if x != 1]:
... 	print item
... 	
2
3

Steve




More information about the Python-list mailing list