properly delete item during "for item in..."

mk mrkafk at gmail.com
Thu Jul 17 12:57:32 EDT 2008


Gary Herron wrote:
> You could remove the object from the list with
>  del myList[i]
> if you knew i.  HOWEVER, don't do that while looping through the list!  
> Changing a list's length will interact badly with the for loop's 
> indexing through the list, causing the loop to mis the element following 
> the deleted item.

Jumping into a thread, I know how not to do it, but not how to do it 
properly?

Iterating over a copy may _probably_ work:

 >>> t=['a', 'c', 'b', 'd']
 >>>
 >>> for el in t[:]:
	del t[t.index(el)]

	
 >>> t
[]


However, is it really safe? Defining safe as "works reliably in every 
corner case for every indexable data type"?


Con: suppose the data structure t is really, really big. Just deleting 
some items from t temporarily doubles the memory consumption.




More information about the Python-list mailing list