6

Here's a simple program:

#!/usr/bin/env python3

l = list(range(5))
print(l, type(l))

l = list(range(5)).remove(2)
print(l, type(l))

for some reason the list is destroyed on removing the element:

[0, 1, 2, 3, 4] <class 'list'>
None <class 'NoneType'>

(it is program output)

I expected it to output

[0, 1, 3, 4]

What is wrong, and how do I remove the element from a list generated with range?

Adobe
  • 12,967
  • 10
  • 85
  • 126

1 Answers1

16

You are storing the return value of the list.remove() call, not the list itself. The list.remove() call alters the list in place and returns None. It does not return the altered list.

Store the list first:

l = list(range(5))
l.remove(2)

or use a list comprehension to filter:

l = [i for i in range(5) if i != 2]
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343