Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove element from a list generated with range in python? [duplicate]

Tags:

python

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?

like image 968
Adobe Avatar asked Dec 11 '22 03:12

Adobe


1 Answers

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]
like image 182
Martijn Pieters Avatar answered May 11 '23 01:05

Martijn Pieters