check if a list is empty in python

Python – Check If a List is Empty – With Examples

In this tutorial, we will look at how to check if a list is empty or not in Python with the help of some examples.

There are a number of ways to check if a list is empty or not in Python. In this tutorial, we will look at the following methods –

  • By calculating the length of the list and checking if its equal to 0.
  • Using the list in a boolean context.

Let’s now take a look at each of the above methods with the help of some examples.

The length of an empty list is zero.

You can use the Python len() function to calculate the length of the list and then compare it with zero to check if the list is empty or not. Here’s an example –

# create two lists
ls1 = []
ls2 = [1,2,3]
# check if list is empty
print(len(ls1)==0)
print(len(ls2)==0)

Output:

True
False

We get True as the output for the list ls1 as it is empty and False for the list ls2 because it’s not empty (has non-zero length).

If you use the list in a boolean context, it will evaluate to True if the list has any elements and it will evaluate to False if the list is empty. Thus, you can use the expression not ls to check if the list ls is empty or not.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

Here’s an example.

# create two lists
ls1 = []
ls2 = [1,2,3]
# check if list is empty
print(not ls1)
print(not ls2)

Output:

True
False

We get the same result as above. True for the list ls1 as it’s empty and False for the list ls2 as it’s not empty (ls2 has three elements).

This method is considered more Python by many and generally used in constructs like the following –

if not ls:
    print("List is empty")
    # do something
else:
    print("List is not empty")
    # do something else

In this tutorial, we looked at two methods to check if a list is empty or not.

Choose the method you’re most comfortable with. Using the length method is more explicit and you can extend it to numpy arrays whereas the second method does not work on numpy arrays (checking if they are empty or not).

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top