How to append to the end of an empty list?

前端 未结 8 1165
终归单人心
终归单人心 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: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)).

提交回复
热议问题