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
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…