Create an empty list in python with certain size

后端 未结 15 1441
有刺的猬
有刺的猬 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
    s1 = []
    for i in range(11):
       s1.append(i)
    
    print s1
    

    To create a list, just use these brackets: "[]"

    To add something to a list, use list.append()

    0 讨论(0)
  • 2020-11-22 12:24

    You cannot assign to a list like lst[i] = something, unless the list already is initialized with at least i+1 elements. You need to use append to add elements to the end of the list. lst.append(something).

    (You could use the assignment notation if you were using a dictionary).

    Creating an empty list:

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

    Assigning a value to an existing element of the above list:

    >>> l[1] = 5
    >>> l
    [None, 5, None, None, None, None, None, None, None, None]
    

    Keep in mind that something like l[15] = 5 would still fail, as our list has only 10 elements.

    range(x) creates a list from [0, 1, 2, ... x-1]

    # 2.X only. Use list(range(10)) in 3.X.
    >>> l = range(10)
    >>> l
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
    

    Using a function to create a list:

    >>> def display():
    ...     s1 = []
    ...     for i in range(9): # This is just to tell you how to create a list.
    ...         s1.append(i)
    ...     return s1
    ... 
    >>> print display()
    [0, 1, 2, 3, 4, 5, 6, 7, 8]
    

    List comprehension (Using the squares because for range you don't need to do all this, you can just return range(0,9) ):

    >>> def display():
    ...     return [x**2 for x in range(9)]
    ... 
    >>> print display()
    [0, 1, 4, 9, 16, 25, 36, 49, 64]
    
    0 讨论(0)
  • 2020-11-22 12:25

    I'm a bit surprised that the easiest way to create an initialised list is not in any of these answers. Just use a generator in the list function:

    list(range(9))
    
    0 讨论(0)
  • 2020-11-22 12:28

    One simple way to create a 2D matrix of size n using nested list comprehensions:

    m = [[None for _ in range(n)] for _ in range(n)]
    
    0 讨论(0)
  • 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}, {}, {}]
    >>> 
    
    0 讨论(0)
  • 2020-11-22 12:30

    I came across this SO question while searching for a similar problem. I had to build a 2D array and then replace some elements of each list (in 2D array) with elements from a dict. I then came across this SO question which helped me, maybe this will help other beginners to get around. The key trick was to initialize the 2D array as an numpy array and then using array[i,j] instead of array[i][j].

    For reference this is the piece of code where I had to use this :

    nd_array = []
    for i in range(30):
        nd_array.append(np.zeros(shape = (32,1)))
    new_array = []
    for i in range(len(lines)):
        new_array.append(nd_array)
    new_array = np.asarray(new_array)
    for i in range(len(lines)):
        splits = lines[i].split(' ')
        for j in range(len(splits)):
            #print(new_array[i][j])
            new_array[i,j] = final_embeddings[dictionary[str(splits[j])]-1].reshape(32,1)
    

    Now I know we can use list comprehension but for simplicity sake I am using a nested for loop. Hope this helps others who come across this post.

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