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 Find the Factorial of a Number
Python zip()
Python sleep()
Python hasattr()
Python Namespace and Scope
Python bytearray()
Python Program to Copy a File
Python List sort()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python Program to Check Armstrong Number
Finding Max/Min of a List or Collection
Python Program to Print the Fibonacci sequence
Python break and continue
Python Program to Represent enum
Python Keywords and Identifiers
Python List remove()
Ways to Iterate Over a List in Java
Python Program to Print all Prime Numbers in an Interval
Python Program to Reverse a Number
Python Program to Transpose a Matrix
Python delattr()
Python Program to Slice Lists
Intelligent Projects Using Python - Santanu Pattanayak
Python String split()
Python String rpartition()
Python datetime
Python List extend()
Python String strip()
Python Program to Display the multiplication Table
Python String expandtabs()
Python Dictionary popitem()
Java – Get Random Item/Element From a List