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 Package
Python filter()
Python Program to Convert Bytes to a String
Python Statement, Indentation and Comments
Python Shallow Copy and Deep Copy
Python Set difference_update()
Python help()
APIs in Node.js vs Python - A Comparison
Python issubclass()
Python frozenset()
Python Program to Print Hello world!
Python String isdecimal()
Python classmethod()
Python Program to Remove Duplicate Element From a List
Python Program to Trim Whitespace From a String
Python complex()
Python Operators
Python str()
Python String translate()
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Get the Full Path of the Current Working Directory
Python Custom Exceptions
Python String find()
Python Program to Check If Two Strings are Anagram
Python String lstrip()
Python hex()
Python Generators
Python *args and **kwargs
Python len()
Python Global, Local and Nonlocal variables
Python vars()
Python Dictionary keys()