> -----Original Message----- > From: [EMAIL PROTECTED] [mailto:python- > [EMAIL PROTECTED] On Behalf Of Ratko > Sent: Thursday, July 17, 2008 12:27 PM > To: python-list@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 -- http://mail.python.org/mailman/listinfo/python-list