How can I create a list of variables in python. for example how can I create the following variables f_1, f_2, f_3, ..., f_100. I want to make them with 'for' loop. is there a function that I can use in this specific problem?
-
Is there any particular reason why you want to create many separately named variables, rather than just use a list object (e.g. `f`) that you then index by number (e.g. `f[3]`)? – alani Jun 06 '20 at 07:37
-
Take a look at https://stackoverflow.com/questions/961632/converting-integer-to-string – mushishi Jun 06 '20 at 07:38
4 Answers
how about a dictionary?
numd = {}
for i in range(100):
numd["f_{}".(i)] = 0
or just make a list then add the values there with a for loop

- 333
- 1
- 8
Using map and range; coercing integers to strings in the lambda function and prefixing the numeric with "f_":
[*map(lambda x: "f_"+str(x), [*range(1, 100)])]
Using a for loop:
numeric_range = [*range(1, 100)]
lst = []
for i in numeric_range:
lst.append("f_"+str(i))
print(lst)
Using a list comprehension:
["f_"+str(i) for i in range(1, 100)]

- 5,682
- 1
- 11
- 15
If you really want to assign new variables dynamically, you could run an assignment command via the exec
function, for example:
for i in range(100):
value = i * 2
var_name = "f_{}".format(i)
exec("{} = {}".format(var_name, repr(value)))
print(f_30)
However, you would need a very strong and specific reason to want to do the above.
The normal expectation would be that you simply put the values into a single list
object, and access it by index number. For example:
f = []
for i in range(100):
value = i * 2
f.append(value)
print(f[30])

- 12,573
- 2
- 13
- 23
If you are ok with it that they are created in the global namespace then you could also use the following code:
for i in range(100):
globals()["f_"+str(i)] = 0
globals()
gets you a dictionary of the names defined in the global namespace.

- 11
- 2