How to append to the end of an empty list?

前端 未结 8 1115
终归单人心
终归单人心 2020-11-27 13:13

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:



        
相关标签:
8条回答
  • 2020-11-27 13:42

    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.

    0 讨论(0)
  • 2020-11-27 13:43

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

    0 讨论(0)
提交回复
热议问题