Create an empty list in python with certain size

后端 未结 15 1639
有刺的猬
有刺的猬 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:30

    The accepted answer has some gotchas. For example:

    >>> a = [{}] * 3
    >>> a
    [{}, {}, {}]
    >>> a[0]['hello'] = 5
    >>> a
    [{'hello': 5}, {'hello': 5}, {'hello': 5}]
    >>> 
    

    So each dictionary refers to the same object. Same holds true if you initialize with arrays or objects.

    You could do this instead:

    >>> b = [{} for i in range(0, 3)]
    >>> b
    [{}, {}, {}]
    >>> b[0]['hello'] = 6
    >>> b
    [{'hello': 6}, {}, {}]
    >>> 
    

提交回复
热议问题