Python doesn’t have a specific built-in function to directly check if a list is empty, but there are several ways to check for an empty list using built-in methods.
Python provides built-in methods like len(), not(), and bool(), and by comparing with an empty list. These methods are used to check if the list is empty or not. In this blog, we’ll explore more about these methods along with examples.
Table of Contents:
Methods to Check if a List is Empty in Python
Python provides various built-in methods and by using these methods, you can check if a list is empty or not. Let’s explore more about these methods with the help of examples:
Method 1: Using the len() method to Check if a List is Empty in Python
The len() method in Python returns the number of elements in a list. So when you use len(new_list), it simply returns the number of elements in the list. If len(new_list) == 0, it means that the list has no elements, and thus the list is considered empty.
Syntax:
len(object)
Example 1: If the list consists of elements
Output:
Example 2: If the list is empty
Output:
Method 2: Using not() Method to Check if a List is Empty in Python
The not() methodis a logical negation operator. It changes the truth value of a condition or expression.
Not true —> false
Not false —> true
It returns true when the operand is false, and returns false when the operand is true. Commonly used for checking false statements or to negate conditions.
Example:
Output:
Method 3: By Comparing with an empty list [ ] to Check if a List is Empty in Python
We can check if the list is empty by comparing it directly with the empty list([ ]), by simply using the equality operator( ==).
Example:
Output:
Method 4: Using bool() Method to Check if a List is Empty in Python
This bool() method is used to convert the value to a boolean in True or False. For example, if the list is empty then the bool(0) returns the “False” and if the list is not empty then the bool(1) returns the “True”.
Syntax
bool(object)
Example:
Output:
Here the bool is assigned to bool(0) so it returns “false” and next it is assigned to bool(1) which returns “true”.
Example: bool() using if-else condition
Output:
Note: The difference between the not() and bool() is
- not(): mostly used for logical negation.
- bool(): converts the value to a boolean (True or False)
Method 5: Using the try-execute Method to Check if a List is Empty in Python
If you try to access the first position of the list, and then if that list is empty, it will raise an IndexError which should be caught in the except block.
Example:
Output:
The output will be “List is empty” because the list doesn’t contain any elements.
Conclusion
In Python, there are several ways to check if a list is empty or not, including using methods like len(), not(), direct comparison to an empty list [ ], bool(), or a try-except block. These approaches help make Python code more readable and efficient.