How do I initialize a list with x positions in Python?

Asked

Viewed 40 times

0

I want to create in the list x empty positions before filling, as I do?

  • 2

    Trivially: [None] * 10; can also do something with range, but it will hardly get simpler than that.

1 answer

2

To solve your problem it will take nothing more than a multiplication... Just as you can create a print() as follows:

print('-' * 10)

Upshot: ----------
You can create a list using the same technique.
This way the code would be like this:

lista = [None] * 50 #o valor 50 pode ser trocado por qualquer um

This will create a lista with 50 positions all filled with the value None which may subsequently be replaced by any other desired value.
To be sure of the result do the following tests:

print(len(lista)) #ira mostrar o tamanho da lista criada. No caso aqui vai aparecer 50.
print(lista) #Mostra toda a lista com os seus valores, se você contar irá ver que possui 50 elementos.

Browser other questions tagged

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