/  Technology   /  How to check if a variable exists in Python?
How to check if a variable exists in Python

How to check if a variable exists in Python?

 

In Python, variables are declared in two ways, locally and globally. A local variable is defined inside a function and a global variable is defined outside the function. 

 

To know more about local and global variables refer to the article local and global variables

 

We can check if a variable exists or not using the following ways

  • Using locals()
  • Using globals()
  • Using hasattr()
  • Using list.count()
  • Using in operator

 

1. Using locals():

This method takes in no attribute but returns a list of all the local variables in the form of a dictionary.

Example:

def method_1():
   print("The Local Variables are:", locals())

def method_2():
   variable = 'I am a variable'
   print("The Local Variable are::", locals())

method_1()
method_2()

Output:

 

2. Using globals():

This built-in function also doesn’t take any parameters. It returns all the information stored in the current global symbol table.

Example:

variable = 'I am a variable'

def method_1():
   print("The Local Variable are:", locals())

method_1()

Output:

 

3. Using hasattr():

This function is used to find the existence of a variable in a class. This function takes two parameters, object and varaiable_name.  It returns a Boolean value, True if the variable is present else False

Example:

class Week:
   name='Sunday'
   name= 1


day = Week()

print('Week has number?', hasattr(day, 'number'))
print('Week has name?', hasattr(day, 'name'))

Output:

 

4. Using list.count():

This function finds the number of occurrences of a given variable in the given list. If the returned value is greater than 0, then it denotes the presence of that variable in the list. It takes one parameter, the variable to be checked.

Example:

list_week = ['Sun','Mon','Tue','Wed']
print(list_week)
var = 'Sun'

print('The variable we are searching is: '+var)

if list_week.count(var)>0 :
   print('The variable is present in the list')
else:
   print('The variable is not present in the list')

Output:

 

5. Using in operator:

The in operator can be used to know the presence of a variable in a list. It returns a Boolean value, True if the variable is present, else False

Example:

list_week = ['Sun','Mon','Tue','Wed']
print(list_week)
var = 'Sun'

print('The variable we are searching is: '+var)

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

Output:

Leave a comment