dynamic variables in python

How to Dynamically Create Variables in Python

Typically, we create variables using literal strings. You need to explicitly write the code to create each variable. But sometimes you may need to programmatically create variables. In other words you may need to dynamically create variables in Python. In this article, we will learn how to create such variables, also known as variable variables in Python.


How to Dynamically Create Variables in Python

There are several ways to create dynamic variables but a simple way to do this is using a dictionary as shown below.

First we create an empty dictionary to hold all variables.

a = {}

Let us say you want to create 5 dynamic variables. For this purpose, we set a counter k=0.

k = 0

Then we just loop till k<5 and in each iteration, use the counter as key and assign the value to the variable, as shown below.

while k < 5:

    # calculate value
    value = ...
    a[k] = value 
    k += 1

You can also assign a separate key if you want, dynamically, as shown below. Here we are dynamically calculating key and using it to create variable.

while k < 10:
    # dynamically create key
    key = ...
    # calculate value
    value = ...
    a[key] = value 
    k += 1

For example, you can dynamically calculate key using uuid4() function.

import uuid
while k < 10:
    # dynamically create key
    key = str(uuid.uuid4())
    # calculate value
    value = ...
    a[key] = value 
    k += 1

In this article, we have learnt a simple way to create dynamic variables in Python. Using a dictionary makes it easy to keep track of all your dynamic variables in one place. However, it is not advisable to use dynamic variables because it gets messy with variable variable names that are hard to track.

Also read:

How to Login to PostgreSQL Without Password
How to Store PostgreSQL Output to File
How to Get Row Count of All Tables in MySQL
How to Get Row Count of All Tables in PostgreSQL
How to Select Every Nth Row in PostgreSQL

Leave a Reply

Your email address will not be published. Required fields are marked *