85

I have a list:

list1=[]

the length of the list is undetermined so I am trying to append objects to the end of list1 like such:

for i in range(0, n):

    list1=list1.append([i])

But my output keeps giving this error: AttributeError: 'NoneType' object has no attribute 'append'

Is this because list1 starts off as an empty list? How do I fix this error?

LostLin
  • 7,514
  • 12
  • 49
  • 73
  • 44
    No -1 please. The fact that append() returns None can trick beginers. The question is genuine. – e-satis Jun 14 '11 at 07:26

8 Answers8

75

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

Andrew Jaffe
  • 25,476
  • 4
  • 47
  • 58
19

You don't need the assignment operator. append returns None.

Mikola
  • 8,867
  • 2
  • 33
  • 41
6

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])
Yuri Stuken
  • 11,890
  • 1
  • 25
  • 23
3

Mikola has the right answer but a little more explanation. It will run the first time, but because append returns None, after the first iteration of the for loop, your assignment will cause list1 to equal None and therefore the error is thrown on the second iteration.

Endophage
  • 20,181
  • 10
  • 56
  • 87
3

I personally prefer the + operator than append:

for i in range(0, n):

    list1 += [[i]]

But this is creating a new list every time, so might not be the best if performance is critical.

Petar Ivanov
  • 88,488
  • 10
  • 77
  • 93
1

Note that you also can use insert in order to put number into the required position within list:

initList = [1,2,3,4,5]
initList.insert(2, 10) # insert(pos, val) => initList = [1,2,10,3,4,5]

And also note that in python you can always get a list length using method len()

Artsiom Rudzenka
  • 26,491
  • 4
  • 32
  • 51
0

Like Mikola said, append() returns a void, so every iteration you're setting list1 to a nonetype because append is returning a nonetype. On the next iteration, list1 is null so you're trying to call the append method of a null. Nulls don't have methods, hence your error.

John
  • 14,488
  • 11
  • 43
  • 64
-3

use my_list.append(...) and do not use and other list to append as list are mutable.

Ranjit
  • 17
  • 6
  • 2
    This answer is hard to understand (I'm not sure what you mean by the second part, for example) and either repeats information from the existing answers (from 2014) or (if taken literally) is flat out wrong (OP's code contains no `my_list` variable). – melpomene Jul 19 '17 at 18:20