0

Lets say I want to produce a number of variables, but the actual amount I am unaware of (as may depend on the input, etc.), the only thing differentiating the variables from one another is a piece of information in their identifier. Is there any way that this is possible in Python 3?

Coded example (using f-strings):

for i in range(3):
  f'variable{i}' = i

print (variable0)
print (variable1)
print (variable2)

Meaning the output of this program would be:

0
1
2
martineau
  • 119,623
  • 25
  • 170
  • 301
0isab
  • 67
  • 2
  • 7
  • 3
    The best way to handle this would be to use a list: `variable = list(range(3))`. Then you can use `variable[i]` to access the individual elements. – Tom Karzes Jun 09 '20 at 17:41
  • Sounds like a XY question. Can you elaborate on why you need multiple variables instead of e.g. a dict? – Christian B. Jun 09 '20 at 17:41
  • @TomKarzes yeah, I think I will probably use lists as they fit the best in my case. Thanks! – 0isab Jun 09 '20 at 17:42
  • I've seen this question come up numerous times, and it always confuses me. How can you use a variable if you don't know ahead of time if it will exist? – Mark Ransom Jun 09 '20 at 19:23

0 Answers0