1

I am removing elements from a list. But using for to iterate through the elements , I can see that alternate elements are being accessed, hence all elements are not getting deleted.

Code

l = ['A','B','C','D','E','F']
for x in l:
    l.remove(x)
    print "My List:"+str(l)
print "Final List:"+str(l)

Output

My List:['B', 'C', 'D', 'E', 'F']
My List:['B', 'D', 'E', 'F']
My List:['B', 'D', 'F']
Final List:['B', 'D', 'F']

Can you please suugest any modification in this logic which would sort the issue. Alternatively if there is a better approach to this.

misguided
  • 3,699
  • 21
  • 54
  • 96

5 Answers5

5

You should not modify the list you are iterating upon, else you are bound to get wierd results.

Rather iterate over a copy of list:

for x in l[:]:
    l.remove(x)
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
1

Instead of deleting elements from the list, you could just slice it:

l = ['A','B','C','D','E','F']
for i in range(len(l) + 1):
    print "My List:"+str(l[i:])
unutbu
  • 842,883
  • 184
  • 1,785
  • 1,677
1

An alternative to copying the list (and would make more sense imo given the context):

In [1]: from collections import deque
In [2]: l = deque(['A','B','C','D','E','F'])
In [3]: while len(l) > 0:
   ...:     l.popleft()
   ...:     print l
   ...:     
deque(['B', 'C', 'D', 'E', 'F'])
deque(['C', 'D', 'E', 'F'])
deque(['D', 'E', 'F'])
deque(['E', 'F'])
deque(['F'])
deque([])
Demian Brecht
  • 21,135
  • 5
  • 42
  • 46
1

How about this? This does not make up any new list.

l = ['A','B','C','D','E','F']
while l: del l[0]; print("My List:"+str(l))

print("Final List:"+str(l))
rnbguy
  • 1,369
  • 1
  • 10
  • 28
0

It seems what you want is just removing all the elements from the list. I think you can just use:

l = []

Or if there is a condition, you can use list comprehension:

[x for x in l in if x ...]
zhangyangyu
  • 8,520
  • 2
  • 33
  • 43
  • `l[:] = []` empties the existing list, so any other references to it will also see the empty list. `l = []` rebinds to a new empty list, so is slightly different – John La Rooy Jul 25 '13 at 22:51
  • Why `l[:] = []` empties `l`? I have tried it is but I don't understand why. `l[:]` is just a copy of `l`. – zhangyangyu Jul 25 '13 at 23:36
  • 1
    @zhangyangyu: `l[:] = ...` is an assignment to a slice of `l`. As a stand-alone expression, `l[:]` is a copy of `l`, but when it is on the left-hand side of an assignment, it means all items in `l` get replaced by the items in the sequence on the right-hand side. You can use other slices as well. For example, `l[2:3] = [40,50,60]` replaces the value at index 2 with `40,50,60`. – unutbu Jul 26 '13 at 01:40
  • Thank you very much! When you say `l[2:3] = [40, 50, 60]`, everything comes obvious.@unutbu – zhangyangyu Jul 26 '13 at 02:06