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

119,750

Solution 1

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) )

Solution 2

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.

Solution 3

You should go back and rethink why you "need" dynamic variables. Chances are, you can create the same functionality with looping through the list, or slicing it into chunks.

Solution 4

If the number of Items doesn't change you can convert the list to a string and split it to variables.

wedges = ["Panther", "Ali", 0, 360]
a,b,c,d = str(wedges).split()
print a,b,c,d

Solution 5

Instead, do this:

>>> var = ['xx','yy','zz']
>>> var[0]
'xx'
>>> var[1]
'yy'
>>> var[2]
'zz'
Share:
119,750
David Yang
Author by

David Yang

Updated on July 15, 2021

Comments

  • David Yang
    David Yang almost 3 years

    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.