Table of Contents
In this example, you will learn to check if a Python list is empty.
To understand this example, you should have the knowledge of the following Python programming topics:
1. Example 1: Using Boolean operation
my_list = []
if not my_list:
print("the list is empty")
Output
the list is empty
If my_list is empty then not returns True.
It is the most pythonic way of testing emptiness. If you want to learn more about boolean truth value, you can refer to Truth Value Testing.
2. Example 2: Using len()
my_list = []
if not len(my_list):
print("the list is empty")
Output
the list is empty
In this example, length of list is used to check if there is any element in the list. If the length of a list is 0, then the list is empty.
3. Example 3: Comparing with []
my_list = []
if my_list == []:
print("The list is empty")
Output
[] is an empty list, therefore if my_list has no elements, then it should be equal to [].
Related posts:
Python Program to Remove Duplicate Element From a List
Python List insert()
Python String isalnum()
Python File I/O Operation
How to Find an Element in a List with Java
Python globals()
Python bytes()
Python frozenset()
Python Program to Check Leap Year
Python Program to Count the Number of Occurrence of a Character in String
Python String center()
How to get current date and time in Python?
Python Program to Randomly Select an Element From the List
Python Program to Get Line Count of a File
Python List
Python String title()
Python Program to Print Output Without a Newline
Python Program to Get the Class Name of an Instance
Python Program to Get File Creation and Modification Date
Python Set remove()
Python Program to Find the Largest Among Three Numbers
Removing all Nulls from a List in Java
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Find the Size (Resolution) of a Image
Python chr()
Python Tuple count()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python sum()
Python *args and **kwargs
Python List append()
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Finding Max/Min of a List or Collection