Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
119 views
in Technique[技术] by (71.8m points)

python - Appending to range function

EDIT: Thank you for your kind replies on how to accomplish what I am trying to do, but the question is about WHY range().append() returns None if you try it in one step, and WHY it works if you two-step the procedure.

Im trying to create a numerical list but with a twist. I don't want a couple of numbers at the beggining of my list:

mlist = [0, 5, 6, 7, ...]

So i thought to do the following:

 mlist = range(5,n+1).append(0)

but silently fails because type(mlist) afterwards equals to NoneType ?! (related: type(range(5,10) evaluates to list Type)

If i try to do that in two steps eg:

>>> mlist = range(5,10)
#and then
>>> mlist.append(0)
>>> mlist
[5, 6, 7, 8, 9, 10, 0]

What's happening?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

list.append() alters the list in place, and returns None. By assigning you assigned that return value to mlist, not the list you wanted to build. This is a standard Python idiom; methods that alter the mutable object never return the altered object, always None.

Separate the two steps:

mlist = range(5, n + 1)
mlist.append(0)

This adds [0] to the end; if you need the 0 at the start, use:

mlist = [0] + range(5, n + 1)

or you can use list.insert(), again as a separate call:

mlist = range(5, n + 1)
mlist.insert(0, 0)

but the latter has to shift up all elements one step and creating a new list by concatenation is the faster option for shorter lists, insertion wins on longer lists:

>>> from timeit import timeit
>>> def concat(n):
...     mlist = [0] + range(5, n)
... 
>>> def insert(n):
...     mlist = range(5, n)
...     mlist.insert(0, 0)
... 
>>> timeit('concat(10)', 'from __main__ import concat')
1.2668070793151855
>>> timeit('insert(10)', 'from __main__ import insert')
1.4820878505706787
>>> timeit('concat(1000)', 'from __main__ import concat')
23.53221583366394
>>> timeit('insert(1000)', 'from __main__ import insert')
15.84601092338562

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...