[Python] How to create a dynamic variable using a for statement! Doesn't Python have a separate function?

Asked 2 years ago, Updated 2 years ago, 15 views

for i in range(10) : var_i = i

It doesn't recognize me like this.

If you write a dictionary, you can tie it with key and value, but

The key value is recognized as str.

Is there a simple way?

python

2022-09-21 21:29

1 Answers

You can use the reflection function

Python is managed by dict when paired, such as 'name' and 'value', as in variables.

>>> import sys
>>> mod = sys.modules[__name__]
>>> for i in range(10):
...     ...     setattr(mod, 'var_{}'.format(i), i)
...     
>>> var_0
0
>>> var_1
1


2022-09-21 21:29

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.