-1

I've recently taken to using an f-string when I input things into lists using for loops - just for better quality of life:

for i in range(3):
array.append(int(input(f"Please input the value for item {i + 1}: ")))

Or:

array = list(int(input(f"Please enter a value for input {x + 1}: ")) for x in range(3))

This got me wondering whether there was a way to create multiple variables in a similar fashion:

for i in range(3):
input{i} = int(input(f"Please input the value for item {i + 1}: "))

Never seen this done before and I don't see a way it could be, but hey, would be cool.

DyingInCS
  • 51
  • 5
  • What is it exactly you want to achieve? What is wrong with storing your variables in a list? – Julien Jan 09 '22 at 11:25
  • 1
    Does this answer your question? [How do you create different variable names while in a loop? (duplicate)](https://stackoverflow.com/q/6181935/6045800) – Tomerikoo Jan 09 '22 at 11:48
  • @Julien was wondering if variables could be created in bulk. But will look more into dictionaries and the possibilities with them. Despite it not being an actual replacement for variable assignment. – DyingInCS Jan 09 '22 at 11:50
  • @Tomerikoo yeah I guess that's more or less what I wanted to do, dictionaries just didn't come to mind. Thanks for the help though. – DyingInCS Jan 09 '22 at 11:58
  • 2
    Note that in general this is not a good idea. Dynamically changing the namespace and creating new variables is bad design (usually) as it quickly becomes hard to keep track of which variables are defined and which not. Using a container (like a list of a dict) makes this much easier. Depending on your exact use-case (which you didn't share), the matching container should be chosen – Tomerikoo Jan 09 '22 at 12:01
  • Yeah, the comment on the thread you shared gave a similar warning. Didn't mention a case because I'm just experimenting right now, this isn't project-specific. Appreciate the help though. – DyingInCS Jan 09 '22 at 12:09

1 Answers1

1

The closest there is to that is using a dictionary:

values = {}

for i in range(3):
    values[i] = int(input(f"Please input the value for item {i + 1}: "))
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Josh Ackland
  • 603
  • 4
  • 19
  • 1
    Not sure what is the benefit of a dict over a list here... – Julien Jan 09 '22 at 11:24
  • There isn't any benefit. The asker is wondering about dynamically creating variable names to store values. Dictionaries are the closest thing there is to creating dynamic variable names as you can name the key. – Josh Ackland Jan 09 '22 at 11:29
  • But having the keys as sequential integers is basically an elaborate list... `dict[0]` and `list[0]` looks exactly the same to the user but using a list is much more efficient in that case... – Tomerikoo Jan 09 '22 at 11:45
  • Ah alright, my knowledge of dictionaries is pretty basic so will be interesting to look into. Thanks for the info :) – DyingInCS Jan 09 '22 at 11:48