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

Reedick, Andrew jr9445 at ATT.COM
Thu Jul 17 21:56:27 CEST 2008



> -----Original Message-----
> From: python-list-bounces+jr9445=att.com at python.org [mailto:python-
> list-bounces+jr9445=att.com at python.org] On Behalf Of Ratko
> Sent: Thursday, July 17, 2008 12:27 PM
> To: python-list at python.org
> Subject: properly delete item during "for item in..."
> 
> 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?
> 
> 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.
> 


Walk the list backwards when deleting.



master = ['a', 'b', 'c', 'd', 'e', 'f', 'g']


print "Deletes nothing"
a = master[:]
print a
for i in a:
	del i
print a

print
print

print "Deletes safely from end"
a = master[:]
print a
for i in range(len(a)-1, -1, -1):
	print i
	if i % 2 == 0:
		print "    removing ", master[i]
		del a[i]
		print "    ", a,
		if master[i] in a:
			print "Ooops, deleted wrong thing...",
		print
print a

print
print

print "Delete from front.  Deletes wrong things and throws an
exception..."
a = master[:]
print a
#for i in range(len(a)-1, -1, -1):
for i in range(len(a)):
	print i
	if i % 2 == 0:
		print "    removing ", master[i]
		del a[i]
		print "    ", a,
		if master[i] in a:
			print "Ooops, deleted wrong thing...",
		print
print a





More information about the Python-list mailing list