1
scores_h1 = []
scores_h2 = []
scores_h3 = []
scores_h4 = []
scores_h5 = []
scores_h6 = []
scores_h7 = []
scores_h8 = []
scores_h9 = []

for i in range(1,10):
   value = int(input("Score: "))
   string = f'scores_h{i}'
   string.append(value)

I am trying to append value to scores_h1 the first time the loop runs. And then the second time to scores_h2 and then the third time to scores_h3 and so on.. Is there a way to do that?

Vihaang01
  • 13
  • 4
  • 1
    Use a list of lists or a dictionary instead of 10 variables. – Guy Nov 15 '21 at 12:30
  • Does this answer your question? [How can I create lists from a list of strings?](https://stackoverflow.com/questions/14241133/how-can-i-create-lists-from-a-list-of-strings) – aneroid Nov 15 '21 at 12:54
  • And [How do I create variable variables?](https://stackoverflow.com/q/1373164/1431750) – aneroid Nov 15 '21 at 12:55

2 Answers2

1

I am unsure this is what you really want, but then the following code does it:

length = 9

lst = [[] for i in range(length)]

for i in range(length):
   value = int(input("Score: "))
   lst[i].append(value)

print(lst)

Basically you do not want 9 independent lists. You want a nested list. Then you can call each list within the top one with the corresponding index.

Output may look like:

[[1], [2], [3], [4], [5], [2], [3], [1], [3]]
Synthase
  • 5,849
  • 2
  • 12
  • 34
0

You can use defaultdict from collections to have a dict of lists:

from collections import defaultdict

lists_dict = defaultdict(list)

for i in range(1,10):
   value = int(input("Score: "))
   lists_dict[f"list_{i}"].append(value)

print(dict(lists_dict))

Output:

{'list_1': [1], 'list_2': [2], 'list_3': [3], 'list_4': [4], 'list_5': [5], 'list_6': [6], 'list_7': [7], 'list_8': [8], 'list_9': [9]}
David Meu
  • 1,527
  • 9
  • 14