2

This is the code I have used and it is not removing last zero it is skipping

x = [1,2,3,0,0,0]


for I in x:
    if I==0:
        x.remove(I)
print(x)

output:

[1, 2, 3, 0]

so from the output the last zero is not removing why

juanpa.arrivillaga
  • 88,713
  • 10
  • 131
  • 172

2 Answers2

1

Why don't you use this simple list comprehension.

x = [1,2,3,0,0,0]
y=[i for i in x if i != 0]
print(y)

You'll get a new list (y) with the 0 removed, while the x is preserved in it's original state.

[1, 2, 3]

Process finished with exit code 0

For more study on list.remove(), check this List.remove() does not remove all occurrances

Anand Gautam
  • 2,018
  • 1
  • 3
  • 8
1

As per documentation, list.remove removes first element whose value matches given number.

So, when first '0' at index 3 is removed, the new list is [1,2,3,0,0] with the list iteration index at 4. The following 0 (which was at index 4 in original list) moves back one place and is getting skipped. This can be seen with following code:

x = [0,0,0,0,0,0]
for id, i in enumerate(x):
    print(id, i)
    if i == 0:
        print(x, i)
        x.remove(i)

print(x)

In this, every second element is missed, and final x is [0, 0, 0]

As for what is correct way to do this, list comprehension is a good way, as answered by Anand: x = [i for i in x if i!=0]

pippo1980
  • 2,181
  • 3
  • 14
  • 30
e_a
  • 61
  • 4