Assign multiple variables at once with dynamic variable names

mikemaccana picture mikemaccana · Mar 11, 2011 · Viewed 45.2k times · Source

I'm aware I can assign multiple variables to multiple values at once with:

(foo, bar, baz) = 1, 2, 3

And have foo = 1, bar = 2, and so on.

But how could I make the names of the variables more dynamic? Ie,

somefunction(data,tupleofnames):
    (return that each name mapped to a single datum)

somefunction((1,2,3),(foo,bar,baz))     

And have the same?

Answer

Thomas K picture Thomas K · Mar 11, 2011

There are ways to do it, but they're not nice ways, and it's considered bad practice in Python. New variables shouldn't be created by magic. If you want to have a collection of things, use a list, dictionary or set, as appropriate.

For example, you could return a dictionary: {"foo":1, "bar":2, "baz":3}