List problem

Cliff Wells clifford.wells at comcast.net
Fri Oct 29 14:32:18 EDT 2004


On Fri, 2004-10-29 at 15:19 -0300, Batista, Facundo wrote:
> [Thomas M.]
> 
> #- test_list = [1, 2, 3] 
> #-  
> #- for i in test_list: 
> #-    print i 
> #-  
> #-    if 1 in test_list: 
> #-       test_list.remove(1)
> 
> As a rule of thumb, never modify a list that you're iterating.
> 
> If you want to modify the list, iterate a copy:
> 
> for i in test_list[:]: 

Another approach (that doesn't require creating a copy of the list) is
to iterate backwards over it:

>>> test_list = [1, 2, 3]
>>> for i in range(len(test_list) - 1, -1, -1):
...     if test_list[i] == 1:
...         test_list.pop(i)
...
1
>>> test_list
[2, 3]
>>>

-- 
Cliff Wells <clifford.wells at comcast.net>




More information about the Python-list mailing list