How do I check if a list is empty in Python?

Often, we need to check if a list is empty . in this Python example we will discuss some o the ways to create a dictionary from separate lists in Python.

Some of the topics which will be helpful for understanding the program implementation better are:

1. Using the len() function

This function returns the number of elements in a list. If a list is empty, len() will return 0,

Now let’s implement a program to check if a list is empty.

fruits = []

if len(fruits) == 0:
  print("The list is empty")
else:
  print("The list is not empty")
Output
The list is empty

2. Using the not operator

The not operator is a logical operator that reverses the truth value of a boolean expression. If a list is empty, the boolean expression not fruits will evaluate to True.

Now lets implement the example again

fruits = []

if not fruits:
  print("The list is empty")
else:
  print("The list is not empty")
Output
The list is empty

3. Using the == operator

This operator compares two values and returns True if they are equal, and False otherwise.

fruits = []

if fruits == []:
  print("The list is empty")
else:
  print("The list is not empty")
Output
The list is empty

4. Using bool() operator

The bool() function returns the boolean value of an object. If a list is empty, bool(fruits) will return False.

fruits = []

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

5. Conclusion

In this Python example, we discussed how to use the len() function, the not operator, the == operator, or the bool() function to check if a list is empty in Python.


Helpful Links

Please follow the Python tutorial series or the menu in the sidebar for the complete tutorial series.

Also for examples in Python and practice please refer to Python Examples.

Complete code samples are present on Github project.

Recommended Books


An investment in knowledge always pays the best interest. I hope you like the tutorial. Do come back for more because learning paves way for a better understanding

Do not forget to share and Subscribe.

Happy coding!! ?

Recommended -

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Index