By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
444,199 Members | 1,209 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 444,199 IT Pros & Developers. It's quick & easy.

Deleting item of list while visting list...

P: 10
I have strange issue when deleting element of list which I'm browsing. Here is the code , please have a look.
Expand|Select|Wrap|Line Numbers
  1. >>> li = ['mike','anil','jassi']
  2. >>> for name in li:
  3.     print name
  4.  
  5. mike
  6. anil
  7. jassi
  8. >>> for name in li:
  9.     print name
  10.     li.remove(name)
  11.  
  12. mike
  13. jassi
  14. >>> li
  15. ['anil']
  16.  
It seems strange, In my project , I have global list , while going thro' each item , I have to delete item upon certain condition. But I'm not getting result as expected whenever it delete element. It seems as upon deletion, List length get decreased and it is causing this behavior (might be As Designed from python or I can use list as this way)

If someone know details behind this behavior of list , pls share (However I got workaround for this issue by using another list and putting element and then deleting 1 by 1 :))

thanks,
Anil
Dec 4 '08 #1
Share this Question
Share on Google+
2 Replies


bvdet
Expert Mod 2.5K+
P: 2,851
Python is doing exactly what you are telling it to do. The first iteration, 'mike' (element 0) is printed, then deleted. The next iteration, element 1 (now 'jassi') is printed, then deleted. The iteration is done at this point.
Dec 4 '08 #2

boxfish
Expert 100+
P: 469
As bvdet said, Python is not adjusting the indexes to account for deleted items. When you delete an item from the list, all the items after it move down one index. Your loop ends up skipping every other element. If you want delete all the items, you can use
Expand|Select|Wrap|Line Numbers
  1. for i in xrange(len(li)):
  2.     print li[0]
  3.     del li[0]
I hope this is helpful.
Dec 4 '08 #3

Post your reply

Sign in to post your reply or Sign up for a free account.