2

I am have a nested list with the following:

[['X', 0],
['X', 0],
['X', ''],
['X', '']]

for i in myList:
    if i[1] == 0:
         myList.remove(i)

This will only remove the first list. Output would be:

[['X', 0],
['X', ''],
['X', '']]

How can I get it for both?

arsenal88
  • 1,040
  • 2
  • 15
  • 32
  • 1
    Don't change a list when you're iterating over it... – DavidG Apr 05 '18 at 12:15
  • 4
    when you `remove(i)`, you change the list you're iterating over. So when you remove element 0, your loop will continue on with element 1, but what previously *was* element 1 is now element 0, because the previous element 0 was removed, so you skip a value. – Zinki Apr 05 '18 at 12:16
  • As above but if you want to use the nethod you are using you will need to iterate over the list in reverse: `for i in reversed(range(len(myList))):` – AndrewK Apr 05 '18 at 12:22
  • Or make a copy of the original list by using `for i in myList[:]` instead. – AndrewK Apr 05 '18 at 12:27

1 Answers1

3

Using a list comprehension . Do not delete an element from a list while iterating over it.

Ex:

s = [['X', 0],
['X', 0],
['X', ''],
['X', '']]

print([i for i in s if i[1] != 0])
Rakesh
  • 81,458
  • 17
  • 76
  • 113
  • 1
    I was writing the same answer, but you were faster. This is a better approach then iterating and changing the original list. – cezar Apr 05 '18 at 12:16
  • 'Do not delete an element from a list while iterating over it.' Yea I knew it was bad practise and the source of why it was not working. Thanks for your input and help :) – arsenal88 Apr 05 '18 at 12:20