How to Check if the Variable Exists in Python

In this article, we will learn how to check if a variable exists in Python. Python variables are either local or global. In this article, we will see how to check for both the local and global variables.

Check if the variable exists: Local Scope

To check the existence of a variable locally, we use locals() function.

  • Syntax : locals()
  • Parameters: no input parameter
  • Return Type:  information stored in the local symbol table

Example 1: To Check if the variable exists Locally

def function1(): 
    print("No Local Variables Present in Function1")
    print("Local Variables:", locals()) 
	
def function2(): 
	var = 'PythonPool'
	print('Local Variable Is Present in Function2')
	print("Local Variables:", locals()) 

function1() 
function2() 

Output:

Example 1: To Check If Variable Exists Locally
Output

In function1, there were no local variables present. As a result, the locals() function returns an empty local symbol table. On the other hand, in function2, we declared one local variable ‘var’ having the value ‘PythonPool’ thus, the locals() function returns a local symbol table containing the variable and its corresponding value.

Example 2: To use locals() to update a variable

def function1(): 
    print("No Local Variables Present in Function1")
    print("Local Variables:", locals()) 
	
def function2(): 
	var = 'PythonPool'
	print('Local Variable Is Present in Function2')
	print("Local Variables:", locals()) 
	
	locals()['var'] = 'Coding with Python'
	
	print("After updating:", locals()) 
	
function1()
function2()

Output:

Example 2: To Use Locals() To Update A Variable
Output

Like in the previous example, here, function1 has no local variable. As a result, the locals() function returns an empty local symbol table. Similarly, in function2, we declared one local variable ‘var’ having the value ‘PythonPool’; thus, the locals() function returns a local symbol table containing the variable and its corresponding value. After that, we tried to update the variable’s value using the locals() method, but as we can see, the variable’s value is not updated.

Check if the variable exists: Global Scope

To check the existence of a variable globally, we use globals() function.

  • Syntax : locals()
  • Parameters: no input parameter
  • Return Type:  information stored in the current global symbol table

Example 1: Check if the variable exists globally

var = 'Python Pool'

def function1(): 
    print('The global present are:')
    print(globals())

function1() 

Output:

Python Code to Check If Variable Exists Globally
Output

As we can see, when the globals() function was invoked, the variables in the global symbol table are displayed on the output screen.

Example2: To Use globals() To Update A Variable

var = 'Python Pool'

print('Before modification:')
print(globals())

globals()['var'] = 'Coding in Python'
print('After modification:')
print(globals())

Output:

To Use globals() To Update A Variable
Output

We can see that using the globals() function, we have updated the value of the global variable ‘var’. The value which is changed is also updated in the symbol table.

Check if a variable exists in a list in Python:

One can check whether a variable exists in a list in different ways. Let us discuss them one by one.

1)Using “in” operator:

We can use the “in” operator to check if a variable is present in a list.

  • Syntax: var in List
  • Return value: True, if the variable is present in the list otherwise, false.
list_color = ['red','blue','orange','green']
var = 'blue'
print('The list is: ' )
print(list_color)
print('The variable we are searching is: '+var)
print()
if var in list_color:
    print('The variable is present in the list')
else:
    print('The variable is not present in the list')

Output:

Check if a variable exists in a list in Python:
Output

In this code, in the list of colors, we used the “in” operator to check whether the color ‘blue’ is present in the list or not.

2) Using list.count()

This function is used to find the number of occurrences of a given variable in the given list. If the value returned by this function is greater than 0, then it affirms the presence of that variable in the list.

Syntax:

list.count(var)

Return Value:

number of occurrences of the given variable in the list

list_color = ['red','blue','orange','green']
var = 'blue'
print('The list is: ' )
print(list_color)
print('The variable we are searching is: '+var)
print()
if list_color.count(var)>0 :
    print('The variable is present in the list')
else:
    print('The variable is not present in the list')

Output:

2) Using list.count() to check variable exists in python
Output

Here, the occurrence of blue is greater than 0, signifying its presence in the list.

Check if the variable exists in URL:

To check whether a given variable is present in a URL, we can simply use the “in” operator.

url = "https://www.google.com"
print('The url is: '+url )
var ='google'
print('The variable we are searching is: '+var)
print()

if var in url:
    print('The variable is present in the url')
else:
    print('The variable is not present in the url')

Output:

python check if variable exists in URL
Output

Check if the variable exists in class:

To check the existence of a variable in class, we can use the hasattr() function.

  • Syntax: hasattr() 
  • Parameter list:
    • object – object whose named attribute is to be checked
    • name – name of the attribute to be searched
  • Return Value: True if the object contains the given named attribute otherwise False
class Student:
    name='Avishek'
    id=101

st = Student()

print('Student has id?', hasattr(st, 'id'))
print('Student has subject?:', hasattr(st, 'subject'))

Output:

python check if variable exists in class
Output

Here, the class has a variable ‘id’ and so it returns True. On the other hand, it has no variable called ‘subject’ and so it returns a False value.

Python check if variable exists then check its value

We already saw how to check for the presence of a variable in different scenarios. We will now see how to retrieve the values of these elements.

1) using globals()

var = 10
print(globals()['var'])
10

2) using getattr()

class Student:
    name='Avishek'
    id=101

st = Student()

print('Student id:', getattr(st, 'id'))
Student id: 101

Must Read

Final Words

In this article, we learned to check if a variable is declared or not in both local and global aspects. We also saw how both functions differ from each other in updating the value of a variable. We also learned how to check for a variable in different scenarios like in a list, class, etc. And finally, we saw how to retrieve the values of these variables.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments