Home > Blockchain >  When i trying to remove elements in a list it is not working can anyone explain me why this is not w
When i trying to remove elements in a list it is not working can anyone explain me why this is not w

Time:01-06

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

This is the code I have used and it is not removing last zero it is skipping 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 whystrong text

CodePudding user response:

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

CodePudding user response:

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)

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]

  •  Tags:  
  • Related