472,127 Members | 1,574 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 472,127 software developers and data experts.

Deleting item of list while visting list...

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
  5. mike
  6. anil
  7. jassi
  8. >>> for name in li:
  9.     print name
  10.     li.remove(name)
  12. mike
  13. jassi
  14. >>> li
  15. ['anil']
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 :))

Dec 4 '08 #1
2 2302
2,851 Expert Mod 2GB
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
469 Expert 256MB
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.

Similar topics

5 posts views Thread by flupke | last post: by
25 posts views Thread by Markus Svilans | last post: by
1 post views Thread by Macca | last post: by
7 posts views Thread by GHZ | last post: by
15 posts views Thread by buddhatown | last post: by
2 posts views Thread by james_027 | last post: by
reply views Thread by leo001 | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.