0

For an assignment, I want to remove all undesirable items in a list. This is an example of code that should remove all 1's from a list; however, when I run it, it returns None. Why is this?

v=[1,2,1,3,1,4,5,55,1]

for i in v:
    if i==1:
        result=v.remove(1)
    else:
        continue
print (result)
barskyn
  • 353
  • 1
  • 3
  • 13

2 Answers2

0

list.remove() mutates the list in-place. The method itself returns None. Print v to see results.

From the docs:

You might have noticed that methods like insert, remove or sort that only modify the list have no return value printed – they return the default None. 1 This is a design principle for all mutable data structures in Python.

pylang
  • 40,867
  • 14
  • 129
  • 121
0

you can filter your list:

Python 2:

v = filter(lambda x: x != 1, v)

Python 3:

v = filter((1).__ne__, v)

The code snippet in the question is basically equivalent to:

while 1 in v: 
    v.remove(1)
Nir Alfasi
  • 53,191
  • 11
  • 86
  • 129