properly delete item during "for item in..."
gherron at islandtraining.com
Thu Jul 17 18:45:01 CEST 2008
> Say you have something like this:
> for item in myList:
> del item
> Would this actually delete the item from the list or just decrement
> the reference counter because the item in myList is not associated
> with name "item" anymore (but still is with myList[itemIndex])? In
> other words, is "item" a temporary reference to myList[itemIndex] or
> is it actually that reference that myList has stored?
The 'del' statement does not delete an object, it deletes a reference to
an object. In this case, the variable item is deleted from the scope,
and the referred-to object will have its reference counter decremented
by 1. (But, as you surmise, not to zero, because the list will still
You could remove the object from the list with
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.
> I am not sure if this question even makes any sense anymore. I've been
> using python for years and never had any problems (and I don't now
> either) but now that I had to revisit c++/STL, I had to deal about
> these issues and was wondering how python does it.
More information about the Python-list