Here are five examples demonstrating how to check if a list is empty in Python using different methods:
1. Using the not
operator:
# Example 1
my_list = []
if not my_list:
print("The list is empty")
else:
print("The list is not empty")
Explanation:
- We initialize an empty list
my_list
. - We use the
not
operator in theif
condition to check if the list is empty. Ifmy_list
is empty,not my_list
evaluates toTrue
, and the code inside theif
block is executed. - If the list is not empty, the code inside the
else
block is executed.
Output:
The list is empty
2. Using the len()
function:
# Example 2
my_list = []
if len(my_list) == 0:
print("The list is empty")
else:
print("The list is not empty")
Explanation:
- We initialize an empty list
my_list
. - We use the
len()
function to get the length of the list. If the length is equal to 0, then the list is empty. - If the length is 0, the code inside the
if
block is executed. Otherwise, the code inside theelse
block is executed.
Output:
The list is empty
3. By comparing to an empty list:
# Example 3
my_list = []
if my_list == []:
print("The list is empty")
else:
print("The list is not empty")
Explanation:
- We initialize an empty list
my_list
. - We compare
my_list
to an empty list[]
. If they are equal, thenmy_list
is empty. - If
my_list
is empty, the code inside theif
block is executed. Otherwise, the code inside theelse
block is executed.
Output:
The list is empty
4. Using a list comprehension:
# Example 4
my_list = []
if not [elem for elem in my_list]:
print("The list is empty")
else:
print("The list is not empty")
Explanation:
- We initialize an empty list
my_list
. - We use a list comprehension
[elem for elem in my_list]
to iterate over each element inmy_list
. Ifmy_list
is empty, the list comprehension will also be empty. - We apply the
not
operator to the list comprehension. If the list comprehension is empty,not
will evaluate toTrue
, indicating thatmy_list
is empty. - If
my_list
is empty, the code inside theif
block is executed. Otherwise, the code inside theelse
block is executed.
Output:
The list is empty
5. Using the all()
function:
# Example 5
my_list = []
if all(not elem for elem in my_list):
print("The list is empty")
else:
print("The list is not empty")
Explanation:
- We initialize an empty list
my_list
. - We use a generator expression
(not elem for elem in my_list)
to create an iterable of boolean values indicating whether each element inmy_list
is empty or not. - We use the
all()
function to check if all elements in the iterable areTrue
. If all elements areTrue
, thenmy_list
is empty. - If
my_list
is empty, the code inside theif
block is executed. Otherwise, the code inside theelse
block is executed.
Output:
The list is empty
These examples demonstrate different ways to check if a list is empty in Python, using various techniques such as boolean expressions, the len()
function, list comparisons, list comprehensions, and the all()
function.
Top comments (0)