python unexpected output for list operation

Viewed 30

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?

1 Answers

It is happening because, the first time i is pointing towards the 1st element, so it removes 12, now i increases and points to the 2nd 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)
Related