Limit when creating a list in Python

Asked

Viewed 906 times

0

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

lista = [[None]]*50

I will have a list of 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 as a result, but if I give len(lista[0]) I will get the result 51 and not 1000. What’s going on? Why are you always giving the total list size + 1 instead of 1000?

1 answer

2


Because what you’re adding to the list is another list of 1000 elements, but even if you have 1000 elements, it only counts as one - because it’s only a single list.

In 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, making:

>>> 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]]
]

Which is a list of lists with 6 elements. That’s right, this is the expected behavior, but it’s not what you expected/desired.

Empty list lists (Python)

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

lista = [[0 for j in range(1000)] for i in range(50)]
  • Another detail is that since lists are passed by reference, all the elements in the list are a reference to the same list; try lista[0] is lista[1] with the original code.

  • 1

    @Pedrovonhertwig Yes, this is explained in the question I mentioned

Browser other questions tagged

You are not signed in. Login or sign up in order to post.