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:
Partition a List in Java
APIs in Node.js vs Python - A Comparison
Python Errors and Built-in Exceptions
Python for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python String islower()
Python print()
Python Strings
Python Program to Convert Decimal to Binary, Octal and Hexadecimal
Python while Loop
Python Set update()
Python String isprintable()
Python super()
Python Program to Find Armstrong Number in an Interval
Ways to Iterate Over a List in Java
Building Chatbots with Python Using Natural Language Processing and Machine Learning - Sumit Raj
Python bytearray()
Python Program to Find the Largest Among Three Numbers
Python ascii()
Python iter()
Python String isalnum()
Python Generators
Python Set add()
Python Exception Handling Using try, except and finally statement
Python next()
Python Program to Sort Words in Alphabetic Order
Python issubclass()
How to Find an Element in a List with Java
Python Program to Find the Factors of a Number
Python String swapcase()
Python String rstrip()
Python Function Arguments
Python String split()