Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why range(0,10).remove(1) does not work?

Tags:

python

list

why

range(0,10).remove(1)

does not work?

I know the question is pretty short, but I do not have any idea why this thing does not work.. Is it possibe to write it in one line?

like image 954
Oren Avatar asked Jan 26 '15 13:01

Oren


2 Answers

x = range(0, 10) will return either a list or a range object (depending on your Python version).

Python 2.x

x = range(0, 10).remove(1) will return None as list.remove will modify the list in-place and so returns None. Your list is created and the value 1 removed, but as it is never assigned to anything, it's garbage collected.

Python 3.x

x = range(0, 10).remove(1) will return an AttributeError as range objects don't have a remove method. If you convert it to a list using list(range(0, 10)).remove(1) you'll have the same issue as Python 2 though.

A way to get what you want would be to use a list comprehension. In the list comprehension you'll iterate over range(0, 10) but use an if statement to only add a value that isn't 1, such as:

x = [i for i in range(0, 10) if i != 1]
# [0, 2, 3, 4, 5, 6, 7, 8, 9]
like image 195
Ffisegydd Avatar answered Oct 18 '22 07:10

Ffisegydd


Because the remove() method operates "in place", and doesn't return anything.

like image 2
FuzzyDuck Avatar answered Oct 18 '22 07:10

FuzzyDuck