Create an empty list in python with certain size

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

    varunl's currently accepted answer

     >>> l = [None] * 10
     >>> l
     [None, None, None, None, None, None, None, None, None, None]
    

    Works well for non-reference types like numbers. Unfortunately if you want to create a list-of-lists you will run into referencing errors. Example in Python 2.7.6:

    >>> a = [[]]*10
    >>> a
    [[], [], [], [], [], [], [], [], [], []]
    >>> a[0].append(0)
    >>> a
    [[0], [0], [0], [0], [0], [0], [0], [0], [0], [0]]
    >>> 
    

    As you can see, each element is pointing to the same list object. To get around this, you can create a method that will initialize each position to a different object reference.

    def init_list_of_objects(size):
        list_of_objects = list()
        for i in range(0,size):
            list_of_objects.append( list() ) #different object reference each time
        return list_of_objects
    
    
    >>> a = init_list_of_objects(10)
    >>> a
    [[], [], [], [], [], [], [], [], [], []]
    >>> a[0].append(0)
    >>> a
    [[0], [], [], [], [], [], [], [], [], []]
    >>> 
    

    There is likely a default, built-in python way of doing this (instead of writing a function), but I'm not sure what it is. Would be happy to be corrected!

    Edit: It's [ [] for _ in range(10)]

    Example :

    >>> [ [random.random() for _ in range(2) ] for _ in range(5)]
    >>> [[0.7528051908943816, 0.4325669600055032], [0.510983236521753, 0.7789949902294716], [0.09475179523690558, 0.30216475640534635], [0.3996890132468158, 0.6374322093017013], [0.3374204010027543, 0.4514925173253973]]
    

提交回复
热议问题