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:
Deep Learning from Scratch - Building with Python form First Principles - Seth Weidman
Deep Learning with Python - Francois Chollet
Python time Module
Python String center()
Partition a List in Java
Python String isalpha()
Python Program to Find LCM
Node.js vs Python for Backend Development
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python List copy()
Python Program to Find the Size (Resolution) of a Image
How to get current date and time in Python?
Python Program to Copy a File
Python Program to Sort Words in Alphabetic Order
Python Program to Check if a Number is Positive, Negative or 0
Python Program to Iterate Through Two Lists in Parallel
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda
Python String zfill()
Python String encode()
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python eval()
Python if...else Statement
Python Program to Convert Bytes to a String
Python filter()
Python Program to Make a Simple Calculator
Python String endswith()
Python Program to Display the multiplication Table
Python List index()
Python Program to Print all Prime Numbers in an Interval
Introduction to Scientific Programming with Python - Joakim Sundnes
Python Program to Check If a String Is a Number (Float)
Python Program to Add Two Matrices