Type error when trying to extend a list in Python

故事扮演 提交于 2019-12-02 11:42:53

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

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

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!

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