To check if list is empty in Python, you can use multiple methods like – if not list_var:
or if len(list_var) == 0:
. There are many ways but not all are very efficient and Pythonic. In this article we will look at all these methods and run a time performance check over them to choose the best for our needs.
Using not
superHeroList = [] if not superHeroList: print('SuperHero List is Empty') else: print('There are superheroes to protect the Earth')
In this code, we are using not
keyword to determine if our superHeroList
is empty.
Using len()
superHeroList = [] if len(superHeroList) == 0: print('SuperHero List length is 0') else: print('We can count on superheroes. They will come')
Here we have used len()
function which will provide the length of list. Then we are checking if this length is equal to 0.
Using == []
superHeroList = [] if superHeroList == []: print('No one will come for our aid') else: print('Justice League is complete')
This example is simple equality check of list with empty list. If they matches then it means our list is empty.
We have 3 methods but which one we should use? To answer this, lets run a time performance test of all these methods to check which one is more efficient –
import timeit import json def check1(): superHeroList = [] if not superHeroList: return True else: return False def check2(): superHeroList = [] if len(superHeroList) == 0: return True else: return False def check3(): superHeroList = [] if superHeroList == []: return True else: return False testFor_CheckEmptyList = { 'not list': min(timeit.repeat(lambda: check1(), number=100)), 'len(list) == 0': min(timeit.repeat(lambda: check2(), number=100)), 'list == []': min(timeit.repeat(lambda: check3(), number=100)), } print(json.dumps(testFor_CheckEmptyList, indent=2))
When I run the benchmark, I got these results –
{ "not list": 2.573244273662567e-05, "len(list) == 0": 3.429688513278961e-05, "list == []": 3.0700117349624634e-05 }
It clearly shows that using not
operator is the best, most efficient and pythonic way of checking the emptiness of list.