Search code snippets, questions, articles...

Check if list is empty in Python

We are going to explain some methods that can be used to check whether a list is empty or not.
my_list = []

if my_list:
  print("List is not empty")
else:
  print("List is empty")
Best JSON Validator, JSON Tree Viewer, JSON Beautifier at same place.

Output

List is empty

We are using Python not keyword here to check whether a list is empty or not. We just need to place not keyword before list variable name and it will return True if the list is empty and False if the list is not empty.

Code Example 2

my_list = [1, 2]

if not my_list:
  print("List is empty")
else:
  print("List is not empty")

Output

List is not empty

Use len() function to check if list is empty

We can use len() function to check whether a list is empty or not. It takes the list as a parameter and returns 0 if the list is empty. We can understand it using the below code example.

my_list = []

if len(my_list) == 0:
  print('This is an empty list')

Output

This is an empty list

Using bool() function

We can also use the bool() function to check whether a list is empty or not. The function will take the list as a parameter and return True if the list has some items and return False if the list is empty.

Syntax

bool(List)

Code example

my_list = []

if bool(my_list):
  print('List is not empty')
my_list = [1, 2, 3]

if bool(my_list):
  print('List is not empty')

# -> List is not empty
Was this helpful?
0 Comments