Type error when trying to extend a list in Python

Question:

I need to understand why :

years = range(2010,2016)
years.append(0)

is possible, returning :

[2010,2011,2012,2013,2014,2015,0]

and

years = range(2010,2016).append(0)

or

years = [0].extend(range(2010,2016))

doesn’t work ?

I understand that it is a type error from the message I got. But I’d like to have a bit more explanations behind that.

Asked By: Dirty_Fox

||

Answers:

You are storing the result of the list.append() or list.extend() method; both alter the list in place and return None. They do not return the list object again.

Do not store the None result; store the range() result, then extend or append. Alternatively, use concatenation:

years = range(2010, 2016) + [0]
years = [0] + range(2010, 2016)

Note that I’m assuming you are using Python 2 (your first example would not work otherwise). In Python 3 range() doesn’t produce a list; you’d have to use the list() function to convert it to one:

years = list(range(2010, 2016)) + [0]
years = [0] + list(range(2010, 2016))
Answered By: Martijn Pieters

append and extend operations on lists do not return anything (return just None). That is why years is not the list you expected.

Answered By: Saksham Varma

In Python 3 range returns an instance of the range class and not a list. If you want to manipulate the result of range you need a list, so:

years = list(range(2010,2016)) 
years.append(2016)

Finally, (and similarly to the append above) extend operates on the list you’re calling it from rather than returning the new list so:

years = list(range(2010,2016))
years.extend( list(range(2016,2020)))

*While Python 2’s range function does return a list, the above code will still work fine in Python 2*

Hope this helps!

Answered By: SteJ