Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to assign each element of a list to a separate variable?

if I have a list, say:

ll = ['xx','yy','zz'] 

and I want to assign each element of this list to a separate variable:

var1 = xx var2 = yy var3 = zz 

without knowing how long the list is, how would I do this? I have tried:

max = len(ll) count = 0 for ii in ll:     varcount = ii     count += 1     if count == max:         break 

I know that varcount is not a valid way to create a dynamic variable, but what I'm trying to do is create var0, var1, var2, var3 etc based on what the count is.

Edit::

Never mind, I should start a new question.

like image 618
David Yang Avatar asked Oct 10 '13 15:10

David Yang


People also ask

How do you assign a list of values to a variable in Python?

Using for inThe for loop can help us iterate through the elements of the given list while assigning them to the variables declared in a given sequence. We have to mention the index position of values which will get assigned to the variables.

How do I assign multiple values to multiple variables?

You can assign the same value to multiple variables by using = consecutively. This is useful, for example, when initializing multiple variables to the same value. It is also possible to assign another value into one after assigning the same value.

Can we assign a list to a variable in Python?

We generally come through the task of getting certain index values and assigning variables out of them. The general approach we follow is to extract each list element by its index and then assign it to variables. This approach requires more line of code.


1 Answers

Generally speaking, it is not recommended to use that kind of programming for a large number of list elements / variables.

However, the following statement works fine and as expected

a,b,c = [1,2,3] 

This is called "destructuring".

It could save you some lines of code in some cases, e.g. I have a,b,c as integers and want their string values as sa,sb,sc:

sa, sb,sc = [str(e) for e in [a,b,c]] 

or, even better

sa, sb,sc = map(str, (a,b,c) ) 
like image 169
cmantas Avatar answered Sep 30 '22 20:09

cmantas