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 RegEx
Python open()
Python Program to Merge Mails
Python String upper()
Python oct()
Python Program to Find the Square Root
Python Program to Find All File with .txt Extension Present Inside a Directory
Python String rindex()
Python Program to Append to a File
Python Operator Overloading
Python sleep()
Java – Get Random Item/Element From a List
Python Program to Get the File Name From the File Path
Python Program to Copy a File
Python String title()
Statistical Methods for Machine Learning - Disconver how to Transform data into Knowledge with Pytho...
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python Program to Display Fibonacci Sequence Using Recursion
Convert a Map to an Array, List or Set in Java
Python Get Current time
Python String isdecimal()
Python Program to Capitalize the First Character of a String
Python Program to Display Calendar
Python Program to Find Armstrong Number in an Interval
Python for Loop
Python Statement, Indentation and Comments
Python List count()
Python bin()
Python Set pop()
Python Program to Compute the Power of a Number
Python bytearray()
Python Program to Find the Sum of Natural Numbers