How to add to the end of an empty list?

I have a list:

list1=[] 

the length of the list is not defined, so I'm trying to add objects to the end of list1, for example:

 for i in range(0, n): list1=list1.append([i]) 

But my conclusion continues to give this error: AttributeError: the object "NoneType" does not have the attribute "add"

Is this because list1 starts as an empty list? How to fix this error?

+44
python
Jun 14 2018-11-11T00:
source share
8 answers

append actually modifies the list. In addition, an item is required, not a list. Therefore, all you need is

 for i in range(n): list1.append(i) 

(By the way, note that in this case you can use range(n) .)

I assume your actual use is more complex, but you can use a list comprehension, which is more python for this:

 list1 = [i for i in range(n)] 

Or, in this case, in Python 2.x range(n) actually creates the list you want already, although in Python 3.x you need list(range(n)) .

+46
Jun 14 '11 at 5:01
source share

You do not need an assignment operator. append returns None.

+12
Jun 14 2018-11-11T00:
source share

Mikola has the correct answer, but a little more explanation. It will work the first time, but since append returns None , after the first iteration of the for loop, your assignment will result in list1 equal to None , and therefore the error will be selected in the second iteration.

+4
Jun 14 '11 at 5:01
source share

append returns None, so in the second iteration, you call the append method from NoneType. Just remove the assignment:

 for i in range(0, n): list1.append([i]) 
+2
Jun 14 2018-11-11T00:
source share

I personally prefer the + operator over append :

 for i in range(0, n): list1 += [[i]] 

But this creates a new list every time, so it may not be the best if the performance is critical.

+1
Jun 14. '11 at 5:27
source share

As Mikola said, append() returns a void, so each iteration you set list1 to nonetype, because append returns nonetype. At the next iteration, list1 is null, so you are trying to call the append null method. Nulls have no methods, hence your mistake.

0
Jun 14 '11 at 5:01
source share

Note that you can also use the insert to put the number in the desired position in the 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 the list length using the len () method

0
Jun 14 '11 at 5:20
source share

use my_list.append (...) and not use, and you can change another list to add to the list.

-one
Jul 19 '17 at 18:07
source share



All Articles