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 break and continue
Python Program to Measure the Elapsed Time in Python
Python Program to Sort a Dictionary by Value
Python Global Keyword
Python Program to Count the Number of Occurrence of a Character in String
Python Program to Find the Largest Among Three Numbers
Python Operators
Python Program to Find ASCII Value of Character
Python pow()
Python Program to Add Two Numbers
Python Program to Reverse a Number
Python List count()
Python Program to Extract Extension From the File Name
Python String count()
Python String format()
Python str()
Python String maketrans()
Python Program to Swap Two Variables
Python Dictionary popitem()
Python format()
Python String upper()
Python String lower()
Python print()
Python __import__()
Python List insert()
Python List pop()
Python Anonymous / Lambda Function
Python time Module
Python Program to Display Powers of 2 Using Anonymous Function
Python Program to Catch Multiple Exceptions in One Line
Python Dictionary update()
Deep Learning with Applications Using Python - Navin Kumar Manaswi