Dynamic variable name

Suppose i have to set

q_variable = 0
a_variable = 0

def stats(choice):
     choice + '_variable' += 1


Here after adding the choice + ‘_variable’ will become string.
If i want to change the q_variable or the a_variable depending on the choice we provide to the function.
How do we do that?

Use a dictionary;

variables = {"q": 0, "a": 0}

def stats(choice):
    variables[choice] += 1


maybe not use vars as the name of the dictionary, as it is a builtin on its own.


Good point, changed it to variables.

As suggested, use dictionary or any other suitable data structure. Because if you create variables dynamically you probably want to access them dynamically as well. Now you have two problems.

You can do what you want but you must consider very-very seriously whether is it what you actually need. As it happens, globals are also kept in dictionary so you can always make your life exciting:

>>> a_variable = 1
>>> q_variable = 2
>>> def stats(choice):
...     globals()[f'{choice}_variable'] +=1
>>> stats('a')
>>> a_variable
>>> stats('a')
>>> a_variable
>>> stats('q')
>>> q_variable

I’m somewhat curious: why would you want to do this? What is your use case?

It seems to me that, if scaled up, this would have a detrimental effect on the readability of the code script as well as a complicated way to code. If things seem to be complicated in Python, there’s usually a better (or a less complicated) way to write the code.

how about something more meaningful, such as choices.

I mean, sure, in an actual application you should never name a variable variables. This is just an example, and without knowing what the purpose of the variable is it’s not possible to select a good name.