39

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.

11
  • 25
    why on earth would you want to do that? Commented Oct 10, 2013 at 15:34
  • 3
    Variables are just names. What is wrong with ll[0], ll[1], ll[2] ... etc? Commented Oct 10, 2013 at 15:35
  • What is the usecase ? Looks like what could rethink your approach Commented Oct 10, 2013 at 15:35
  • 2
    Please see Keep data out of your variable names Commented Oct 10, 2013 at 15:40
  • 1
    If you don't know how long the list is, how would you expect to name all the variables? Commented Oct 10, 2013 at 15:50

7 Answers 7

67

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" or "unpacking".

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) )
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for this answer, this is what I came here looking for. Didn't have an interpreter in front of me, and wanted to know if problem, solution = "1+1=2".split("=") was valid, given that split() returns an array rather than 2 values
Not sure what you mean. If None is part of the "result" statement, eg a,b = None, 1, then it will be assigned to the according variable (in this case a).
This is a great feature of python (aka "tuple unpacking"), and it is often useful in cases like the problem, solution = ... situation described by @JHixson... But it does not match the OP's stated condition of not knowing how long the list is.
What if my list has, say, between 1 and 3 arguments? Is there a way to specify that variables 2 and 3 are optional? Using * seems to only allow one optional variable, not several. Thank you
if you do a, *b, c = [1, 2, 3, 4, 5], then b will end up being a list containing [2,3,4]. This can handle from zero to any number of "in-between" elements. Do you mean create a variable that might or might not be defined after the assignment? (eg a,b,c,d = [1,2] where, b,c are not defined in this case?). I'm not aware of something like that (without using conditionals). But more importantly: why? And, even if you could do it, how would later logic handle the variables that might or might not exist?
31

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.

Comments

12

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.

4 Comments

+1 - Sometimes, the best answer is to not answer but instead to say "this isn't good".
You may be right. I guess lists was a simplification. What I'm really dealing with is a Dataframe of unknown length that I have to parse into a format that is compatible with API calls. Which means I'm basically creating a dictionary for every "line" of the dataframe. In that case, I'll have to create the same number of distinct dictionaries anyway, so I thought I'd just create variables instead. I'll keep thinking about it
that is compatible with API calls, its seems a XY problem. You should state the actual problem, rather than how you are assuming you need to solve it
Sounds like you should start a new question, asking for advice on how to solve the problem in a different way instead of ways to make your solution work.
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

2 Comments

this actually works for what I need - converting an array to individual args in a function parameter list
Creating a string from the list just to split it up again makes no sense at all. This will lose type information, add extra punctuation to the results, and possibly fail when one of the lists is... anything remotely interesting. A nested list or tuple, a multi-word string...
1

Instead, do this:

>>> var = ['xx','yy','zz']
>>> var[0]
'xx'
>>> var[1]
'yy'
>>> var[2]
'zz'

1 Comment

I dont like it. The purpose of assigning to to have their own name.
-1

I have found a decent application for it. I have a bunch of csv files which I want to save as a dataframe under their name:

all_files = glob.glob(path + "/*.csv")
name_list = []
for f in all_files:
    name_list.append(f[9:-4])
for i,n in enumerate(name_list):
    globals()[n] = pd.read_csv(all_files[i])

2 Comments

That doesn't look like a decent application, though?
This is the same technique as in existing answers, so it's not clear what this adds.
-1

This should do it (though using exec is not recommended):

for num in range(len(your_list)):
    exec('var'+str(num)+' = your_list[num]')

1 Comment

Do not ever use exec on data that could ever possibly come, in whole or in part, directly or indirectly, from outside the program. It is a critical security risk that enables the author of that data to run arbitrary code. It cannot reasonably be sandboxed (i.e. without defeating the purpose).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.