Open In App

How to check if a Python variable exists?

Last Updated : 22 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Variables in Python can be defined locally or globally. There are two types of variables first one is a local variable that is defined inside the function and the second one are global variable that is defined outside the function. 

Method 1: Checking the existence of a local variable

To check the existence of variables locally we are going to use the locals() function to get the dictionary of the current local symbol table. 

Python3
def func():

  # defining local variable
    a_variable = 0

  # for checking existence in locals() function
    if 'a_variable' in locals():
        return True

# driver code
print(func())

Output:

True

Method 2: Checking the existence of a global variable

To check the existence of variables globally we are going to use the globals() function to get the dictionary of the current global symbol table. 

Python3
# defining local variable
a_variable = 0

def func():  

  # for checking existence in globals() function
    if 'a_variable' in globals():
        return True

# driver code
print(func())

Output
True

Method 3: Testing if a Variable Is Defined or not using try and except

A NameError exception is raised when attempting to access a variable that hasn’t yet been defined, you can manage this with a try/except statement

Python3
# a_variable = 0

try:
    a_variable
    print("Yes")
except NameError:
    print("Error: No value detected")

Output:

Error: No value detected

Using the ‘in’ keyword:

Approach:

You can use the ‘in’ keyword to check if a variable is defined or not.

Python3
if 'my_variable' in locals():
    print('Variable exists')
else:
    print('Variable does not exist')

Output
Variable does not exist

Time complexity: O(1)
Space complexity: O(1)


Previous Article
Next Article

Similar Reads

Check if a variable is string in Python
While working with different datatypes, we might come across a time, when we need to test the datatype for its nature. This article gives ways to test a variable against the data type using Python. Let's discuss certain ways how to check variable is a string. Check if a variable is a string using isinstance() This isinstance(x, str) method can be u
2 min read
Python | Check if variable is tuple
Sometimes, while working with Python, we can have a problem in which we need to check if a variable is single or a record. This has applications in domains in which we need to restrict the type of data we work on. Let's discuss certain ways in which this task can be performed. Method #1: Using type() This inbuilt function can be used as shorthand t
6 min read
How To Check If Variable Is Empty In Python?
Handling empty variables is a common task in programming, and Python provides several approaches to determine if a variable is empty. Whether you are working with strings, lists, or any other data type, understanding these methods can help you write more robust and readable code. In this article, we will see how to check if variable is empty in Pyt
3 min read
Python | Check if element exists in list of lists
Given a list of lists, the task is to determine whether the given element exists in any sublist or not. Given below are a few methods to solve the given task. Method #1: Using any() any() method return true whenever a particular element is present in a given iterator. C/C++ Code # Python code to demonstrate # finding whether element # exists in lis
5 min read
Python | Check if a list exists in given list of lists
Given a list of lists, the task is to check if a list exists in given list of lists. Input : lst = [[1, 1, 1, 2], [2, 3, 4], [1, 2, 3], [4, 5, 6]] list_search = [4, 5, 6] Output: True Input : lst = [[5, 6, 7], [12, 54, 9], [1, 2, 3]] list_search = [4, 12, 54] Output: False Let’s discuss certain ways in which this task is performed. Method #1: Using
4 min read
Python | Check if tuple exists as dictionary key
Sometimes, while working with dictionaries, there is a possibility that it's keys be in form of tuples. This can be a sub problem to some of web development domain. Let's discuss certain ways in which this problem can be solved. Method #1 : Using in operator This is the most recommended and Pythonic way to perform this particular task. It checks fo
7 min read
Python: Check if a File or Directory Exists
Sometimes the need to check if the folder exists in python, and check whether a directory or file exists becomes important because maybe you want to prevent overwriting the already existing file, or maybe you want to make sure that the file is available or not before loading it. So to check how to check if a Directory Exists without exceptions in P
5 min read
Check if a value exists in a DataFrame using in & not in operator in Python-Pandas
In this article, Let’s discuss how to check if a given value exists in the dataframe or not.Method 1 : Use in operator to check if an element exists in dataframe. C/C++ Code # import pandas library import pandas as pd # dictionary with list object in values details = { 'Name' : ['Ankit', 'Aishwarya', 'Shaurya', 'Shivangi', 'Priya', 'Swapnil'], 'Age
3 min read
Check if Table Exists in SQLite using Python
In this article, we will discuss how to check if a table exists in an SQLite database using the sqlite3 module of Python. In an SQLite database, the names of all the tables are enlisted in the sqlite_master table. So in order to check if a table exists or not we need to check that if the name of the particular table is in the sqlite_master table or
2 min read
Check if a string exists in a PDF file in Python
In this article, we'll learn how to use Python to determine whether a string is present in a PDF file. In Python, strings are essential for Projects, applications software, etc. Most of the time, we have to determine whether a string is present in a PDF file or not. Here, we'll discuss how to check f a string exists in a PDF file in Python. Here, w
2 min read
Practice Tags :
three90RightbarBannerImg