Best way to check if a list is empty

Tags: list python
Question!

For example, if passed the following:

a = []

How do I check to see if a is empty?

By : Ray Vega


Answers

Demo:

tasks = ['task1', 'task2']    
# create new list

if len(tasks) == False:
   print("empty")
'''
# There are many ways to check whether a List/Tuples/String is empty!
# method 1:
# if len(tasks) is False:
# method 2:
# if len(tasks) == False:
# method 3:
# if len(tasks) == 0:
# method 4:
# if len(tasks) is 0:
# method 5:
# if not tasks:
# method 6:
# if bool(tasks):
# method others ...

enter image description here

By : xgqfrms


You can even try using bool() like this

    a = [1,2,3];
    print bool(a); # it will return True
    a = [];
    print bool(a); # it will return False

I love this way for checking list is empty or not.

Very handy and useful.



You could also do :

if len(a_list):
    print "it's not empty"


This video can help you solving your question :)
By: admin