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

Are there any code examples left?
Made with love
This website uses cookies to make IQCode work for you. By using this site, you agree to our cookie policy

Welcome Back!

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign in
Recover lost password
Or log in with

Create a Free Account

Sign up to unlock all of IQCode features:
  • Test your skills and track progress
  • Engage in comprehensive interactive courses
  • Commit to daily skill-enhancing challenges
  • Solve practical, real-world issues
  • Share your insights and learnings
Create an account
Sign up
Or sign up with
By signing up, you agree to the Terms and Conditions and Privacy Policy. You also agree to receive product-related marketing emails from IQCode, which you can unsubscribe from at any time.
Creating a new code example
Code snippet title
Source