0

im looking for a way to make variables using a for loop, since the only other way would be way to repetitive. I saw some similar stuff online which looks kinda like this:

for i in range(10):
      globals()[f"my_variable_{i}"] = i

The problem with this is i get a LocalUnboundError, saying the variable referenced before assignment, but the weird thing i found while making some tests is that it doesnt work in that specific area of code, if i use it somewhere else, it works fine.

  • 1
    I remember that when I started learning Python I tried to create numbered variables like in other languages. However, data are stored in Python as lists, and you can easily access data via their index `i`. Information retrieval like `for i, item in enumerate(mylist)` and list indexing `mylist[i]` is the Pythonic way to store and retrieve data. Why do you need those variable names? – Mr. T Jan 15 '22 at 14:08
  • Well im trying to make a program that goes through all possible combination given the alphabet. Also if you dont mind, could you give me an example code to how i would use this? Thanks for the help – idkwhattoputhere Jan 15 '22 at 14:32

0 Answers0