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 Get Line Count of a File
Python reversed()
Python Data Structures and Algorithms - Benjamin Baka
Python oct()
Python Inheritance
Python callable()
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Capitalize the First Character of a String
Python Multiple Inheritance
Python String partition()
Python Program to Concatenate Two Lists
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Program to Convert String to Datetime
Python Program to Safely Create a Nested Directory
Python frozenset()
Python zip()
Python if...else Statement
Machine Learning with Python for everyone - Mark E.Fenner
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python Dictionary items()
Python Program to Find HCF or GCD
Python Program to Reverse a Number
Python bool()
Python List insert()
Python Objects and Classes
Python Program to Differentiate Between type() and isinstance()
Python bytearray()
Python abs()
Python Program to Merge Mails
Converting a List to String in Java
Python setattr()
Python Program to Solve Quadratic Equation