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:
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python list()
Python Dictionary clear()
Python Program to Delete an Element From a Dictionary
Python min()
Python frozenset()
Python Custom Exceptions
Python Program to Check Leap Year
Python String replace()
Converting between an Array and a List in Java
Python print()
Python Program Read a File Line by Line Into a List
Python String format()
Python datetime
Python String zfill()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Set difference_update()
Python Program to Count the Number of Occurrence of a Character in String
Convert a Map to an Array, List or Set in Java
Python Set symmetric_difference()
Python Global, Local and Nonlocal variables
Python pow()
Python Program to Capitalize the First Character of a String
Removing all Nulls from a List in Java
Python callable()
Python Program to Find Hash of File
Python __import__()
Python String lstrip()
Python String rindex()
Python Program to Find Sum of Natural Numbers Using Recursion
Python List count()
Python String lower()