python unexpected output for list operation

Question:

i wanted to remove all elements form list individually using list.remove(element)
so, i made code:

a=[12,34,23]
for i in a:
    a.remove(i)
print(a)

But I got:

[34]

Why did this happen?

Asked By: CaptainPotato

||

Answers:

It is happening, because the first time i is pointing towards the first element, it removes 12, now i increases and points to the second element, and the second element now is 23 and not 34, so it removes 23.

To fix this error, you can do something like:

a = [12, 34, 23]
for i in a:
   a.remove(0)
print(a)
Answered By: Shaurya Goyal
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.