Contents
Python – Check if List is Empty
To check if Python List is empty, you can write a condition if the length of the list is zero or not; or you can directly use the list reference along with not operator as a condition in if statement.
Following is the syntax to use not operator and the list as a condition to check if the list is empty.
if not myList:
statement(s)
In the above Python If statement, statement(s) inside if block execute only if myList
is not empty.
Following is the syntax to use the length of list to form a condition to check if the list is empty.
if len(myList) == 0:
statement(s)
If the list is empty, then there would be zero or no elements in the list. Use builtin function len() and pass the list as argument. len() function returns an integer representing the number of elements in the list. If the list is empty, len() returns 0 and the condition len(myList)==0
becomes True.
Example 1: Check if List is Empty
In the following program, we will initialize an empty list, and check programmatically if the list is empty or not using not operator and list reference.
Python Program
myList = []
if not myList:
print('The list is empty.')
else:
print('The list is not empty.')
Run Output
The list is empty.
Example 2: Check if List is Empty using len()
In the following program, we will initialize an empty list, and check programmatically if the list is empty or not using len() function.
Python Program
myList = []
if (len(myList) == 0):
print('The list is empty.')
else:
print('The list is not empty.')
Run Output
The list is empty.
Summary
In this tutorial of Python Examples, we learned how to check if a Python List is empty or not.
Related Tutorials
- Python – List of Strings
- Python Program to Find Unique Items of a List
- Python Program to Find Smallest Number in List
- Python List of Dictionaries
- How to Insert Item at Specific Index in Python List?
- Python – How to Create an Empty List?
- Python List with First N Elements
- How to Get List of all Files in Directory and Sub-directories?
- Python – Count the items with a specific value in the List
- Python – Convert List to Dictionary
Quiz - Let's see if you can answer these questions
Q1: Which of the following represents an empty List?
Q2: Which of the following statement returns an empty List?
Q3: What is the length of an empty List?
Q4: Which of the following condition returns True for an empty List myList
?