Winterflags Winterflags - 7 months ago 15
Python Question

Python: Set many variables to the same value – with automatic count of number of variables

I want to create a lot of variables, all containing the same value.

Currently, I do this:

foo, bar, qaxx, spat = ("1Value4All",)*4

I would like to keep the code footprint at a minimum (one line here), but at the same time it's troublesome if there are many variables, because I have to assign the number of variables (
) manually.

Can this be done without manual count of the number of variables – instead automatically assigning it to

If the variables could be placed in a list, the number if items in that list could be iterated. But something like this is not possible because the variables become referenced before assignment.

my_variables = [foo, bar, qaxx, spat, dung, polo]

for v in my_variables:
v = "1Value4All"

Edit: The data types for the variables will always be
(Not lists, dicts, sets.)


You can chain all the variables together in one line.

foo = bar = qaxx = spat = "1Value4All"

Edit: Below you state your data is either string or NoneType. This would work for both.

>>> foo = bar = None
>>> type(foo); type(bar)
<type 'NoneType'>
<type 'NoneType'>
>>> foo = bar = "1Value4All"
>>> type(foo); type(bar)
<type 'str'>
<type 'str'>