Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign multiple variables at once with dynamic variable names

Tags:

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?

like image 858
mikemaccana Avatar asked Mar 11 '11 12:03

mikemaccana


People also ask

Can you assign multiple variables at once?

You can assign multiple values to multiple variables by separating variables and values with commas , . You can assign to more than three variables. It is also possible to assign to different types. If there is one variable on the left side, it is assigned as a tuple.

How do you assign multiple values to multiple variables in a single line declaration?

When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.


1 Answers

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}

like image 75
Thomas K Avatar answered Oct 17 '22 07:10

Thomas K