
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Best Way to Check if a List is Empty in Python
A List in Python is a mutable sequence of elements separated by commas ",". It is represented by square braces "[ ]".An empty list contains no elements, meaning its length is 0. It is indicated by the square braces with no elements in it.
In this article, we will explore various methods to check whether a given list in Python is empty.
Checking for an Empty List using Not Operator
In Python, the not operator is one of the logical operators. If the given condition is True, it will return False and vice versa. This operator evaluates the empty list as False. The 'not' operator is the best way to check if a list is empty.
When used with a conditional statement, the not operation of an empty list is considered as True, and the corresponding block is executed.
my_list = [] #input list print("Given list :",my_list) if not my_list: print("The given list is empty.") else: print("The given list is not empty.")
Following is the output of the above code -
Given list : [] The given list is empty.
Checking for an Empty List using len() Function
The len() is a built-in function used to determine the length of the given object. When a list is passed as an argument to len(), it returns the number of elements in the list. If the function returns 0, then the list is considered empty.
my_list = [] #input list print("Given list :",my_list) my_length = len(my_list) #length of the list if my_length == 0: print("The given list is empty.")
Following is the output of the above code -
Given list : [] The given list is empty.