Limit when creating a list in Python

0

With the following command, I can create a list in Python:

lista = [[None]]*50

I'll have a list of lists with 50 units. However, if I create a list this way:

lista = [[None]]*50

for l in lista:
    l.append([0]*1000)

If I give len(lista) I will have 50, but if I give len(lista[0]) I will have the result 51 and not 1000. What is happening? Why are you always giving the total size of the list + 1 instead of 1000?

    
asked by anonymous 12.06.2018 / 20:58

1 answer

2

Because what you are adding to the list is another list of 1000 elements, but even having 1000 elements, it only counts as one - because it is only a single list.

When doing:

>>> lista = [[None]]*5
>>> print(lista)
[
    [None], 
    [None], 
    [None], 
    [None], 
    [None]
]

You will have a list of 5 objects, that each object is a list with 1 object ( None ).

After, doing:

>>> for l in lista:
...     l.append([0]*2)
>>> print(lista)
[
    [None, [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], 
    [None, [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], 
    [None, [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], 
    [None, [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]], 
    [None, [0, 0], [0, 0], [0, 0], [0, 0], [0, 0]]
]

What is a list of lists with 6 elements. That's right, this is expected behavior, but it's not what you expected / wanted.

Lists of empty lists (Python)

To create the array you need, of 50 rows and 1000 columns, you need to do:

lista = [[0 for j in range(1000)] for i in range(50)]
    
12.06.2018 / 21:10