Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to check if a list is empty in Python?
In Python, a list is an ordered sequence that can hold several object types, such as integers, characters, or floats. In this article, we will show you how to check if the given input list is empty or not using Python.
Below are the 5 methods to accomplish this task ?
Using the NOT Operator
In Python, empty lists evaluate to False in boolean context. The not operator provides the most Pythonic way to check for empty lists ?
# Non-empty list
numbers = [1, 2, 3, 4, 5]
if not numbers:
print('Empty list')
else:
print('List is not empty:', numbers)
List is not empty: [1, 2, 3, 4, 5]
Let's test with an empty list ?
# Empty list
empty_list = []
if not empty_list:
print('Empty list')
else:
print('List is not empty:', empty_list)
Empty list
Using the len() Function
The len() function returns the number of elements in a list. An empty list has length 0 ?
# Empty list
items = []
if len(items) == 0:
print('Empty list')
else:
print('Not empty list')
Empty list
Comparing with an Empty List
You can directly compare a list with an empty list [] using the equality operator ?
# Empty list
data = []
if data == []:
print('Empty list')
else:
print('List is not empty:', data)
Empty list
Using __len__() Method
The __len__() method is the underlying implementation that len() calls. However, using len() directly is preferred ?
# Empty list
values = []
if values.__len__() == 0:
print('Empty list')
else:
print('Not empty list')
Empty list
Using NumPy Module
When working with NumPy arrays, you can check the size attribute to determine if the array is empty ?
import numpy as np
# Empty list
numbers = []
# Convert list to NumPy array
array = np.array(numbers)
if array.size == 0:
print('Empty list')
else:
print('List is not empty')
Empty list
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
not list |
Excellent | Fastest | General use (Pythonic) |
len(list) == 0 |
Good | Fast | When length matters |
list == [] |
Good | Slower | Direct comparison needs |
list.__len__() |
Poor | Fast | Avoid (use len() instead) |
NumPy size
|
Good | Slower | When working with arrays |
Conclusion
The not operator is the most Pythonic and efficient way to check for empty lists. Use len() when you need the actual count, and NumPy's size when working with arrays.
