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.
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.
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.
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.
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) )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With