How can you dynamically create variables?

In this tutorial, we will learn How can you dynamically create variables which we can do in several ways like using a dictionary, Local and global keywords, setattr() build function, and even by using class and we will understand all one by one here with examples.


Dynamically Variables

dynamical Variables are the variables we create at the time if running the program there are a number of ways to create it and will discuss the here:

Using Dictionary

In this method we first we create a dictionary where we used the key as the names of the variables we need and values as the values of the variables. for an example of this method look at the code given below

# Dynamically create variables using a dictionary
var_name = "dynamic_ variable"
value = 10
my_ dict = {}
my_ dict[ var_name] = value

# Access the dynamically created variable
print( my_ dict[ var_name])  # Output: 10

Here it will keep on creating new variables as the elements of the dictionary.

Using Local() and Global() Function

It creates the variable dynamically as local and Global

# Dynamically create variables using strings
var_ name = "dynamic_ variable"
value = 10
globals()[ var_ name] = value

# Access the dynamically created variable
print( dynamic_ variable)  # Output: 10

Here is an example that shows how we could create the variable dynamically.

# Creating dynamic variables using locals()
def create_ dynamic_ var():
    var_ name = 'dynamic_ var_1'
    value = 10
    locals()[ var_ name] = value
    print( dynamic_ var_1) # Output: 10

create_ dynamic_ var()


Using setattr() Function

It is an inbuilt function we could create the variables dynamically and can be used during the execution of the program the example is given below:

# Creating dynamic variables using setattr()
class MyClass:

obj = MyClass()
setattr( obj, 'dynamic_ var_1', 10)
print( obj. dynamic _var_1) # Output: 10

Here we created the variable dynamically.

Using a Class

We can create a class and after creation, we may dynamically add attributes to the class to create the variable Dynamically during the execution of the program. To do so look at the example given below.

# Creating dynamic variables using a class
class MyClass:

obj = MyClass()
obj. dynamic_var_1 = 10
obj. dynamic_var_2 = 'Hello'

Here we created a class to create different variables at the time fo requirements at running time.


To learn more about How can you dynamically create variables visit: Create the variable Dynamically in Python.

To learn more about python solutions of different problems and tutorials of solutions along with different concepts of python visit: Python Tutorials And Problems.

To learn more about different other solutions related to different programming languages and concepts related to them visit: beta python programming languages Solutions

Leave a Comment

%d bloggers like this: