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 Dictionary
Python String isspace()
Python vars()
Python bin()
Python String zfill()
Python Errors and Built-in Exceptions
Python Generators
Python Directory and Files Management
Python Program to Find All File with .txt Extension Present Inside a Directory
Python List reverse()
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Check If a String Is a Number (Float)
Python datetime
Java – Get Random Item/Element From a List
Python Package
Python Program to Delete an Element From a Dictionary
Python Dictionary items()
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Python reversed()
Python property()
Python File I/O Operation
Python Program to Calculate the Area of a Triangle
Python Program to Get File Creation and Modification Date
Python __import__()
Python 3 for Absolute Beginners - Tim Hall & J.P Stacey
Python Program to Reverse a Number
Python complex()
Python compile()
Python Program to Merge Mails
Python Program to Count the Number of Occurrence of a Character in String
Python Program to Find HCF or GCD
Python Set intersection()