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?
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.
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.
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}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With