How to append to the end of an empty list?

前端 未结 8 1114
终归单人心
终归单人心 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:26

    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.

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

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

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

    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.

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

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

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

    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])
    
    0 讨论(0)
  • 2020-11-27 13:39

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

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