Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Assign Function to a Variable in Python
Next article icon

How To Print A Variable's Name In Python

Last Updated : 31 Jan, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In Python, printing a variable's name can be a useful debugging technique or a way to enhance code readability. While the language itself does not provide a built-in method to directly obtain a variable's name, there are several creative ways to achieve this. In this article, we'll explore five simple methods to print a variable's name in Python.

Print A Variable Name In Python

Below are the example of How To Print A Variable's Name In Python.

  • Using locals() Function
  • Using globals() Function
  • Using a Custom Function
  • Using inspect module

Print A Variable's Name Using locals() Function

In this example, the below code defines a function `print_variable` that takes a variable as an argument, finds its name within the local scope using list comprehension with `locals()`, and prints the variable name.

Python3
def print_variable(variable):     variable_name = [name for name, value in locals().items() if value is variable][0]     print(f"Variable name using locals(): {variable_name}")  # Example usage: my_variable = 42 print_variable(my_variable) 

Output
Variable name using locals(): variable

Print A Variable's Name Using globals() Function

In this example, below code defines a function print_variable that takes a variable as an argument, finds its name within the global scope using list comprehension with globals(), and prints the variable name.

Python3
def print_variable(variable):     variable_name = [name for name, value in globals().items() if value is variable][0]     print(f"Variable name using globals(): {variable_name}")  # Example usage: global_variable = "Hello, World!" print_variable(global_variable) 

Output
Variable name using globals(): global_variable

Print A Variable's Name Using a Custom Function

In this example, below code defines a function get_variable_name that takes an object and a namespace as arguments, finds the object's name within the given namespace using list comprehension, and returns the variable name.

Python3
def get_variable_name(obj, namespace):     return [name for name, value in namespace.items() if value is obj][0]  # Example usage: custom_variable = [1, 2, 3] custom_variable_name = get_variable_name(custom_variable, locals()) print(f"Variable name using custom function: {custom_variable_name}") 

Output
Variable name using custom function: custom_variable

Print A Variable's Name Using inspect Module

In this example, below code uses the inspect module to define a function `get_var_name` that takes a variable as an argument and prints its name by inspecting the local variables in the current frame. It then calls this function with a variable named `variable` having a value of 42. Note: Using `==` for value comparison might be more appropriate in this context instead of `is`.

Python3
import inspect  def get_var_name(var):     current_frame = inspect.currentframe()     try:         frame_locals = current_frame.f_back.f_locals         var_name = [name for name, value in frame_locals.items() if value is var][0]         print(f"Variable name: {var_name}")     finally:         del current_frame  variable = 42 get_var_name(variable) 

Output
Variable name: variable

Next Article
Assign Function to a Variable in Python

K

kasoti2002
Improve
Article Tags :
  • Python
  • Geeks Premier League
  • Geeks Premier League 2023
Practice Tags :
  • python

Similar Reads

  • Get Variable Name As String In Python
    In Python, getting the name of a variable as a string is not as straightforward as it may seem, as Python itself does not provide a built-in function for this purpose. However, several clever techniques and workarounds can be used to achieve this. In this article, we will explore some simple methods
    3 min read
  • Print Single and Multiple variable in Python
    In Python, printing single and multiple variables refers to displaying the values stored in one or more variables using the print() function. Let's look at ways how we can print variables in Python: Printing a Single Variable in PythonThe simplest form of output is displaying the value of a single v
    2 min read
  • __name__ (A Special variable) in Python
    Since there is no main() function in Python, when the command to run a python program is given to the interpreter, the code that is at level 0 indentation is to be executed. However, before doing that, it will define a few special variables. __name__ is one such special variable. If the source file
    2 min read
  • How to get a variable name as a string in PHP?
    Use variable name as a string to get the variable name. There are many ways to solve this problem some of them are discussed below: Table of Content Using $GLOBALSUsing $$ OperatorUsing debug_backtrace()Using get_defined_vars() and array_search()Method 1: Using $GLOBALS: It is used to reference all
    3 min read
  • Assign Function to a Variable in Python
    In Python, functions are first-class objects, meaning they can be assigned to variables, passed as arguments and returned from other functions. Assigning a function to a variable enables function calls using the variable name, enhancing reusability. Example: [GFGTABS] Python # defining a function de
    4 min read
  • How to use Variables in Python3?
    Variable is a name for a location in memory. It can be used to hold a value and reference that stored value within a computer program. the interpreter allocates memory and decides what can be stored in the reserved memory. Therefore, by assigning different data types to the variables, you can store
    3 min read
  • How to print spaces in Python3?
    In this article, we will learn about how to print space or multiple spaces in the Python programming language. Spacing in Python language is quite simple than other programming language. In C languages, to print 10 spaces a loop is used while in python no loop is used to print number of spaces. Foll
    2 min read
  • How to check if a Python variable exists?
    Checking if a Python variable exists means determining whether a variable has been defined or is available in the current scope. For example, if you try to access a variable that hasn't been assigned a value, Python will raise a NameError. Let’s explore different methods to efficiently check if a va
    4 min read
  • Unused variable in for loop in Python
    Prerequisite: Python For loops The for loop has a loop variable that controls the iteration. Not all the loops utilize the loop variable inside the process carried out in the loop. Example: C/C++ Code # i,j - loop variable # loop-1 print("Using the loop variable inside :") # used loop vari
    3 min read
  • How To Print Unicode Character In Python?
    Unicode characters play a crucial role in handling diverse text and symbols in Python programming. This article will guide you through the process of printing Unicode characters in Python, showcasing five simple and effective methods to enhance your ability to work with a wide range of characters Pr
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences