Create an empty list in python with certain size

后端 未结 15 1643
有刺的猬
有刺的猬 2020-11-22 12:00

I want to create an empty list (or whatever is the best way) that can hold 10 elements.

After that I want to assign values in that list, for example this is supposed

15条回答
  •  一整个雨季
    2020-11-22 12:20

    Try this instead:

    lst = [None] * 10
    

    The above will create a list of size 10, where each position is initialized to None. After that, you can add elements to it:

    lst = [None] * 10
    for i in range(10):
        lst[i] = i
    

    Admittedly, that's not the Pythonic way to do things. Better do this:

    lst = []
    for i in range(10):
        lst.append(i)
    

    Or even simpler, in Python 2.x you can do this to initialize a list with values from 0 to 9:

    lst = range(10)
    

    And in Python 3.x:

    lst = list(range(10))
    

提交回复
热议问题