How to assign each element of a list to a separate variable?
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) )
Not a good idea to do this; what will you do with the variables after you define them?
But supposing you have a good reason, here's how to do it in python:
for n, val in enumerate(ll):
globals()["var%d"%n] = val
print var2 # etc.
Here, globals()
is the local namespace presented as a dictionary. Numbering starts at zero, like the array indexes, but you can tell enumerate()
to start from 1 instead.
But again: It's unlikely that this is actually useful to you.