how to create dynamic variable names in python
for i in range(0, 9):
globals()[f"my_variable{i}"] = f"Hello from variable number {i}!"
print(my_variable3)
# Hello from variable number 3!
how to create dynamic variable names in python
for i in range(0, 9):
globals()[f"my_variable{i}"] = f"Hello from variable number {i}!"
print(my_variable3)
# Hello from variable number 3!
Dynamic Variable declaration in Python
#1st example
user_input = raw_input("Enter a variable name : ")
Enter a variable name: number
globals()[user_input] = 25
# you can use locals to assign local variable
# This is dynmic variable declaration
#2nd example
Class Table:
def __init__(self,x,y,datalist):# here x and y are no. of rows and column and datalist is 2d list
for i in range (x):
for j in range (y):
var = f'table{i}_{j}'
locals()[var] = datalist[i][j]
# here we extracted data from a list of variable length and assigned them to different variable
# this can be helpful in many situations
can we make dynamic variable in pytohn?
# Yes, globals() gives excess to all the global variables.
# globals() is a dictionary that has 'variable' : 'value' as key, value pairs...
# You may use something like
for i in range(100):
globals()['variableno_{1}'.format(i)] = "My name is variableno_{1}".format(i)
# this loop creates 100 different variable in global scope same like assigning...
# variableno_0 = "My name is variableno_1"
# variableno_1 = "My name is variableno_2"
# variableno_2 = "My name is variableno_3"
....
....
# variableno_97 = "My name is variableno_97"
# variableno_98 = "My name is variableno_98"
# variableno_99 = "My name is variableno_99"
creating dynamic variable in python
for i in range(0, 9):
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us