How to assign the elements of a list to different variables in Python?

-1

I have a list, like the following:

lista = [1, 2, 3, 4, 5]

Even though I do not know how many elements are in the list, how do I assign each element of the list to a different variable? (as in the example below)

elemen1 = '1'
elemen2 = '2'
elemen3 = '3'
elemen4 = '4'
elemen5 = '5'
    
asked by anonymous 28.11.2018 / 14:30

1 answer

3

This?

lista = [1, 2, 3, 4, 5]
a, b, c, d, e = lista

See running on ideone . And at Coding Ground . Also I placed GitHub for future reference .

You can do this with the tuple engine, where you can set variables in sequence and the list will automatically populate them. Of course, you need to beat the number of elements with that of variables, otherwise some elements will not go into the variables or some variables will be worthless.

Almost always this does not make sense and does not bring advantages. A variable accessed by its index is still a variable. Especially a variable such as the same distinguished name only one a sequential number shows that is the wrong choice. In very few cases where an API works one way and there is much advantage in another way it should do this.

    
28.11.2018 / 14:34