List problem

User 1 at 2.3
Sun Oct 31 13:32:11 CET 2004


On Fri, 29 Oct 2004 17:52:03 +0000 (UTC), Steven Bethard
<steven.bethard at gmail.com> wrote:

>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:

Unless you're using a while loop and iterating in reverse, for
example:

a = [0,1,2,3,4]
pos_max = len(a) - 1	# Maximum iterable element
pos = pos_max		# Current element
while pos >= 0:
	if a[pos] == 2:
		a.remove(2)
    		pos_max = pos_max - 1
  	pos = pos - 1


>
>>>> 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