0

I have a list

test_list = [1,2,3,4,5]

I want to iterate over the elements of this list and delete them after using. But when I try to do this

for element in test_list:
    print element
    test_list.remove(element)

Alternate elements are printed and removed from test_list

1
3
5
print test_list
[2, 4]

Please explain why this happens!

nimeshkiranverma
  • 1,408
  • 6
  • 25
  • 48

2 Answers2

2

Read the answers to strange result when removing item from a list to understand why this is happening.

If you really need to modify your list while iterating do this:

>>> items = ['x', 'y', 'z']
>>> while items:
...     item = items.pop()
...     print item
...
z
y
x
>>> items
[]

Note that this will iterate in reverse order.

Community
  • 1
  • 1
Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
1

in python this concept is called an iterator

my_iter = iter(my_list)

each time you consume or look at an element it becomes gone ...

Joran Beasley
  • 110,522
  • 12
  • 160
  • 179