+4 votes
in Programming Languages by (5.2k points)
edited by
I want to use some dynamic variables in my programs. The variable name will have some fixed characters and a number appended to it.

E.g

x_1, x_2, x_3,..., etc.

Is there any way to declare dynamic variables in Python?

1 Answer

0 votes
by (33.0k points)

You can use either vars() or globals() built-in method to generate dynamic variable names in python.

Syntax is:

vars()[variable_name]

globals()[variable_name]

Here are examples to show how to use these methods to generate dynamic variable names in python:

Using vars()

I am generating variables x_0, x_1,...,x_4.

>>> for i in range(5):
...     vars()['x_' + str(i)] = 2**i
...
>>> x_1
2
>>> x_2
4
>>> x_3
8
>>> x_4
16
>>> x_0
1
>>> x_1+x_2
6


Using globals()

I am generating variables y_0, y_1,...,y_4.

>>> for i in range(5):
...     globals()['y_' + str(i)] = 2**i
...
>>> y_1
2
>>> y_2
4
>>> y_3
8
>>> y_4
16
>>> y_0
1
>>> y_1+y_3
10

...