Type error when trying to extend a list in Python

落花浮王杯 提交于 2019-12-02 17:26:45

问题


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.


回答1:


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))



回答2:


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




回答3:


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!



来源:https://stackoverflow.com/questions/31734042/type-error-when-trying-to-extend-a-list-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!