How to append to the end of an empty list?
append
actually changes the list. Also, it takes an item, not a list. Hence, all you need is
for i in range(n):
list1.append(i)
(By the way, note that you can use range(n)
, in this case.)
I assume your actual use is more complicated, but you may be able to use a list comprehension, which is more pythonic for this:
list1 = [i for i in range(n)]
Or, in this case, in Python 2.x range(n)
in fact creates the list that you want already, although in Python 3.x, you need list(range(n))
.
You don't need the assignment operator. append returns None.
append
returns None, so at the second iteration you are calling method append
of NoneType. Just remove the assignment:
for i in range(0, n):
list1.append([i])