Python: Check list is empty or not

Given a Python list, we have to check whether it is an empty or not.
Submitted by Nijakat Khan, on July 15, 2022

There are multiple approaches to check the given list is empty or not. Here, we are discussing some of them.

Method 1: Using len() method

The len() method is used to check the length of a list, tuple, dictionary, string, etc.

Syntax:

A=len(list)

The statement will return the length of list and stores it in variable A.

Example 1:

# Defining a list 
l = []

# Checking the list is empty or not 
if len(l)==0: 
   print("list is empty") 
else: 
   print("list is not empty")

Output:

list is empty

Below is another same example, but here the list is not empty.

Example 2:

# Defining a list 
l = ["a", "b", "c"]

# Checking the list is empty or not 
if len(l)==0: 
   print("list is empty") 
else: 
   print("list is not empty")

Output:

list is not empty

Method 2: Using bool() method

The bool() method is used to return the result in the form of true and false. If the condition is true it will return true else it will return false.

Syntax:

l = bool(list)

If the list is true (if there is some element in the list) it will return true and if the list is false (if the list is empty) it will return false.

Example 3:

# Defining an empty list 
list=[]

if bool(list):
    print ("list is not empty")
else:
    print ("list is empty")

Output:

list is empty

Method 3: Using the if else condition

This statement is used to check the condition, if the if condition is true, it will execute the block code of the if statement otherwise it will execute the block code of the else statement.

Syntax:

if statement:
    # code block
else:
    # code block

There are different ways to check if the list is empty or not using the if else condition.

Example 4:

# Defining an empty list 
l= []

# Checking the list is empty or not
if not l:
    print ("list is empty")
else:
    print ("list is not empty")

Output:

list is empty

Example 5:

# Defining an empty list 
list=[]

# Checking whether list is empty or not
if list==[]:
    print ("List is empty")
else:
    print ("List is not empty")

Output:

List is empty

Python List Programs »



Related Programs



Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.