Use a dictionary; variables = {"q": 0, "a": 0} def stats(choice): variables[choice] += 1 stats("q") Answer from abessman on discuss.python.org
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ dynamic variable names - is there a better way?
r/learnpython on Reddit: Dynamic variable names - is there a better way?
August 29, 2022 -

numDays will not be hardcoded like in the example below, but will change according to user input.

Example of what I'm trying to do:

numDays = 2;

eventLabel = "Conference"

event_day1 = ' '

event_day2 = ' '

event_day3 = ' '

i = 0

while i <= numDays:

event_day(i+1) += eventLabel;

i += 1

print(event_day1)

print(event_day2)

print(event_day3)

Expected output:

Conference

Conference

Conference

EDIT: Thank you so much for the responses! They were very helpful!

Discussions

python - How can you dynamically create variables? - Stack Overflow
This is the only way that I know ... indexes dynamically, e.g. if you change which container you are looking inside of. 2016-11-16T19:38:23.587Z+00:00 ... Stuffing things into the global and/or local namespaces is not a good idea. Using a dict is so some-other-language-ish ... d['constant-key'] = value just looks awkward. Python is ... More on stackoverflow.com
๐ŸŒ stackoverflow.com
Dynamic variable names
You might think you want this but you really don't. Not having predictable variable names at runtime is a recipe for broken code. https://www.reddit.com/r/learnpython/wiki/faq#wiki_how_do_i_make_variable_variables.3F More on reddit.com
๐ŸŒ r/learnpython
6
2
May 17, 2021
Trying to create a loop to create dynamic variables
globals()[f"server{i}"] Don't do that though. Use a dictionary, or a list. More on reddit.com
๐ŸŒ r/learnpython
7
1
January 23, 2022
trying to dynamically name and reference a dataframe, getting error 'SyntaxError: can't assign to function call'
General rule of thumb - if you need dynamically created variable names - you are doing something wrong. Even though it is possible, doing so would be an awfully bad idea, ie how will you then reference these variables later in your code? More on reddit.com
๐ŸŒ r/learnpython
4
1
May 5, 2017
๐ŸŒ
Esri Community
community.esri.com โ€บ t5 โ€บ python-questions โ€บ create-dynamic-variable-from-returned-value โ€บ td-p โ€บ 1185872
Solved: Create dynamic variable from returned value / vari... - Esri Community
July 7, 2022 - You can use __getattr__() and __setattr__() built in methods on global/local namespaces to get/set variables by string name on an object or module. See: https://docs.python.org/3.7/library/functions.html#getattr and https://docs.python.org/...
๐ŸŒ
Delft Stack
delftstack.com โ€บ home โ€บ howto โ€บ python โ€บ python dynamic variable name
Python Dynamic Variable Name | Delft Stack
December 14, 2023 - The combination of the locals() function and the update() method offers another dynamic approach to creating variable names within the local scope. This method is particularly useful when you need to create variables dynamically within a specific ...
๐ŸŒ
Sololearn
sololearn.com โ€บ en โ€บ Discuss โ€บ 3015787 โ€บ how-to-create-a-dynamic-variable-in-python
How to create a dynamic variable in python
Sololearn is the world's largest community of people learning to code. With over 25 programming courses, choose from thousands of topics to learn how to code, brush up your programming knowledge, upskill your technical ability, or stay informed about the latest trends.
Find elsewhere
๐ŸŒ
Python Forum
python-forum.io โ€บ thread-23500.html
Changing a variable's name on each iteration of a loop
Is it possible in python to change the name of a variable on each iteration of a loop? For example: for i in range(10): variableNameToChange+i='iterationNumber=='+str(i)I know this won't work, and you can't assign to an operator, but how would y...
๐ŸŒ
CodeSpeedy
codespeedy.com โ€บ home โ€บ how to create dynamic variable name in python
How to create dynamic variable name in Python - CodeSpeedy
September 18, 2021 - In Python, the for loop and the globals() function are used to construct a dynamic variable name.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ changing-variable-names-with-python-for-loops
Changing Variable Names With Python For Loops - GeeksforGeeks
February 26, 2024 - Using globals() method to create dynamically named variables Here we are usi ... In Python, we often use loops to iterate over a collection like list or string. But sometimes, we may want to know when the loop has reached its end.
๐ŸŒ
Medium
medium.com โ€บ geekculture โ€บ a-cool-way-to-dynamically-create-variables-in-python-7c20c12f4f23
A Cool Way To Dynamically Create Variables In Python | by Liu Zuo Lin | Geek Culture | Medium
April 17, 2023 - # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x1060c9a10>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/Users/lzl/Documents/repos/test/a.py', '__cached__': None, 'a': 100, 'b': 200, 'c':300, 'd':400} ^ if we set more variables, they appear in the globals() dictionary too.
๐ŸŒ
Quora
quora.com โ€บ How-can-I-change-the-name-of-a-variable-in-a-loop-in-Python
How to change the name of a variable in a loop in Python - Quora
Answer (1 of 13): Hello! I have a good and bad news for you. I start with the bad one. Producing a new variable name at each iteration of a for loop isnโ€™t a good idea. So I will give you a way to use Python `list` instead, to achieve the same thing. But now the good one: what you wanted to do a...
๐ŸŒ
LinkedIn
linkedin.com โ€บ pulse โ€บ dynamic-ways-creating-variables-python-akhil-pathirippilly-mana
Dynamic ways of creating variables in python
February 11, 2022 - So If you are planning to use this just to create local dynamic variable , this is not the method for you. But yes, globally you can do as follows (You need to make sure you are not overwriting any global variables which are already loaded by system or program unintentionally. ) 3. Using setattr built-in method: setattr(obj, name, value) will call self.__setattr__ dunder method and will set value assigned to "name" argument as attribute name and value assigned to "value" argument as its original value.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-program-to-create-dynamically-named-variables-from-user-input
Python program to create dynamically named variables from user input - GeeksforGeeks
July 23, 2025 - Here we are using the locals() method for creating dynamically named variable and later assigning it some value, then finally printing its value.
๐ŸŒ
MP4Moviez
pakainfo.com โ€บ home โ€บ python โ€บ python dynamic variable name โ€“ how to create a dynamic variable name in python?
Python Dynamic Variable Name - How To Create A Dynamic Variable Name In Python? - Pakainfo
for i in range(0, 9): globals()[f"my_variable{i}"] = f"Welcome from variable number {i}!" print(my_variable3) # Welcome from variable number 3! for x in range(0, 9): globals()['string%s' % x] = 'Welcome' # string0 = 'Welcome', string1 = 'Welcome' ... string8 = 'Welcome' name = "a" value = True player_message = {name: value} print(player_message["a"]) Donโ€™t Miss : How To Read And Write Files In Python 3? I hope you get an idea about python dynamic variable name.
๐ŸŒ
DEV Community
dev.to โ€บ chintanonweb โ€บ beyond-static-embracing-dynamic-variable-creation-in-python-57ol
Beyond Static: Embracing Dynamic Variable Creation in Python - DEV Community
April 8, 2024 - One way to dynamically create variables in Python is by utilizing the globals() function. This function returns a dictionary representing the current global symbol table, which contains all the variables defined in the global scope.
๐ŸŒ
Medium
medium.com โ€บ @nchristiansen โ€บ dynamic-variable-declaration-in-python-6258604ea86
Dynamic Variable Declaration in Python | by Noah Christiansen | Medium
June 15, 2019 - Just like lists (another Python datatype), dictionaries are mutable, so values can be changed or added. However, dictionaries differ from lists in that elements are accessed using keys instead of index numbers. In this way, dictionaries function very similar to their namesake (a comparison I only realized after a student suggested it to me) โ€” youโ€™re looking for the definition (value) of a word (key), and to do so you have to search through the dictionary for the word so you can find the definition associated with it.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnpython โ€บ dynamic variable names
r/learnpython on Reddit: Dynamic variable names
May 17, 2021 -

Hi,

Is there a way to create variable dynamically through a loop?

For instance: aList = [1, 2, 3, 4, 5, 6]

I want all odd numbers in their own set of variables like 1o = [1] 1e = [2] 2o = [3] 2e = [4] And so on

What Iโ€™ve tried:

AList = [1, 2, 3, 4, 5, 6] num = 1

For i in aList: If i % 2 == 0: List(num, โ€˜eโ€™).append(i) Else: List(num, โ€˜oโ€™).append(i)

I get that I need an assignment somewhere but I canโ€™t figure it out

Thanks!

๐ŸŒ
sqlpey
sqlpey.com โ€บ python โ€บ python-dynamic-variable-creation-techniques
Python Techniques for Dynamic Variable Name Creation - โ€ฆ
October 29, 2025 - # Inspect initial global variables (excluding internal names) initial_globals = {k: v for k, v in globals().items() if not k.startswith("__")} print("Initial globals keys:", list(initial_globals.keys())) # Dynamically create 10 new variables for index in range(1, 11): new_var_name = f"dynamic_setting_{index}" globals()[new_var_name] = index * 10 print("\nAccessing new variables:") print(f"dynamic_setting_1 is: {dynamic_setting_1}") print(f"dynamic_setting_2 is: {dynamic_setting_2}") # Inspect the namespace after modification final_globals = {k: v for k, v in globals().items() if not k.startswi
๐ŸŒ
Codingdeeply
codingdeeply.com โ€บ home โ€บ python: 5 best techniques to generate dynamic variable names
Python: 5 Best Techniques to Generate Dynamic Variable Names - Codingdeeply
February 23, 2024 - In Python, dynamically named variables can be generated using methods like globals(), locals(), exec(), for loops, or dictionaries. Each approach has benefits and drawbacks, and the best way should be chosen based on the unique use situation.