How To Check If Variable Is Empty In Python? (original) (raw)
Last Updated : 14 Feb, 2024
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 Python.
Check If Variable Is Empty In Python
Below are some of the ways by which we can check if the variable is empty in Python or not:
- Using len() function
- Using not Keyword
- Using the None Value
- Using Custom Function
Check If Variable Is Empty Using len() function
In this example, the code checks if the length of the list (`my_list`) is zero using `len()`. If the length is zero, it prints "Empty Variable"; otherwise, it prints "Not Empty Variable," providing a simple way to determine whether the list is empty or not.
Python `
my_list = []
if len(my_list) == 0: print("Empty Variable") else: print("Not Empty Variable")
`
Check If Variable Is Empty Using not Keyword
In this example, the code checks if the string variable `my_list` is empty by evaluating its truthiness. If the string is empty, it prints "Empty Variable"; otherwise, it prints "Not Empty Variable," illustrating a concise way to ascertain whether the string is empty or not.
Python3 `
my_list = ""
if not my_list: print("Empty Variable") else: print("Not Empty Variable")
`
Check If Variable Is Empty Using the None Value
In this example, the code checks if the dictionary variable `my_dict` is set to `None`. If the variable is `None`, it prints "empty variable"; otherwise, it prints "not empty variable," demonstrating a straightforward way to determine whether the dictionary is empty or not.
Python3 `
my_dict = None
if my_dict is None: print("empty variable") else: print("not empty variable")
`
Check If Variable Is Empty Using Custom Function
In this example, the code defines a function `is_string_empty` that checks whether a given string (`my_string`) is empty. The function returns `True` if the string is `None` or if its stripped version has zero length. Two strings, `my_string1` and `my_string2`, are then evaluated using this function.
Python `
def is_string_empty(my_string): return my_string is None or len(my_string.strip()) == 0
my_string1 = "opkr" my_string2 = ""
if is_string_empty(my_string1): print("String 1 is empty.") else: print("String 1 is not empty.")
if is_string_empty(my_string2): print("String 2 is empty.") else: print("String 2 is not empty.")
`
Output
String 1 is not empty. String 2 is empty.