Reputation: 3
I am trying to delete the items from a list with this code:
lst = [1, 0, 0, 0, 1, 0, 0, 1]
for i in lst:
lst = lst.remove(i)
print lst
but it gives an error. Could someone help me understand what the problem is?
Upvotes: 0
Views: 81
Reputation: 18221
The problem is that list.remove
returns None
, so when you set lst = lst.remove(i)
, you are replacing lst
by None
, so at the next iteration, you will be trying to apply remove
to None
, which is not possible. Removing the assignment, you no longer get an error;
>>> for i in lst:
... lst.remove(i)
... print lst
...
[0, 0, 0, 1, 0, 0, 1]
[0, 0, 1, 0, 0, 1]
[0, 0, 0, 0, 1]
[0, 0, 0, 1]
Note that if you iterate over a list while removing in this way, you are effectively skipping over every other element, which is why the loop above would appear to end prematurely:
>>> lst = [1, 2, 3, 4, 5, 6, 7, 8]
>>> for i in lst:
... lst.remove(i)
... print(lst)
...
[2, 3, 4, 5, 6, 7, 8]
[2, 4, 5, 6, 7, 8]
[2, 4, 6, 7, 8]
[2, 4, 6, 8]
Upvotes: 3
Reputation: 477
remove
function is used when you want to remove a specific value from list, not by the index.
If you want to remove an item from list by index use
lst.pop(i).
Upvotes: 0