0

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?

1
  • What error are you getitng? Commented Nov 29, 2016 at 20:41

2 Answers 2

3

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]
Sign up to request clarification or add additional context in comments.

1 Comment

You're welcome! If you found the answer useful, you may also want to accept it.
0

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).

Link to documentation

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.