0

I want to have a for loop or similar that can instantiate variables in the loop, and then be available afterward. I know we often print things in for loops, but I want to actually be able to create variable names that correspond the loop number the for loop is on, and save something to that variable.

For example, suppose I have the below for loop:

value = 10

for i in range(5):
    value = i + value
    print(value)

for which I will get print output:

10
11
13
16
20

But what if I want to actually create a new variable with each loop, with some prefix of my choosing like var, so the first variable could end up being called var_one (which would be 10 here), the second var_two, etc.?

I want to create:

var_one = "Something"
var_two = "Something"
etc... in a loop

Make sure to notice how the suffixes are real English words!

Sash Sinha
  • 18,743
  • 3
  • 23
  • 40
  • First step - you need to tell people what programming language you are using. – David Ljung Madison Stellar May 05 '22 at 19:24
  • The usual answer for this is "save the results in an array / vector / dictionary / whatever indexed data structure your language supports". – Raymond Chen May 05 '22 at 19:26
  • David, yes, my bad. Python in my case – michael douglas May 06 '22 at 12:52
  • @RaymondChen Yup, since this is Python, a `list` would be a good fit – wjandrea Jul 30 '22 at 18:50
  • You can could use a [dictionary](https://docs.python.org/3/tutorial/datastructures.html#dictionaries) along with [`num2words`](https://pypi.org/project/num2words/): `from num2words import num2words;print({f'var_{num2words(i).replace("-", "_")}': i for i in range(1, 11)});`. **Output:** `{'var_one': 1, 'var_two': 2, 'var_three': 3, 'var_four': 4, 'var_five': 5, 'var_six': 6, 'var_seven': 7, 'var_eight': 8, 'var_nine': 9, 'var_ten': 10}` – Sash Sinha Jul 30 '22 at 19:46
  • vars()[f'var_{value}'] = value – Arifa Chan Jul 30 '22 at 20:03

0 Answers0