Suppose you are writing a Python program and you want to check if a list is empty. How would you do it? This should be something that is very straightforward right? Or is it?

The example could be a list of fruits that you are keeping track of. The list can be something like the following.

fruits = [ 'apple', 'orange', 'strawberry', 'peach', 'lemon' ]

Suppose you want to check if the list of fruits is empty.

fruits = []

You may be tempted to write code such as the following:

if len(fruits) == 0:
  print('There are no fruits')

Checking if the length of a list is zero is no longer preferred. It works but not preferred. Many programmers have even called it unpythonic.

How about checking the list itself?

if fruits = []:
  print('There are no fruits')

It works but this is also not preferred.

The preferred method is the following:

if not fruits:
  print('There are no fruits')

This is the pythonic way from the PEP 8 Style Guide.

Check Performance

There is a reason the preferred method is preferred. To check the performance, you can time how long each operation takes.

>>> import timeit
>>> min(timeit.repeat(lambda: len([]) == 0, repeat=200))
0.0980069637298584
>>> min(timeit.repeat(lambda: [] == [], repeat=200))
0.09142899513244629
>>> min(timeit.repeat(lambda: not [], repeat=200))
0.07426309585571289
>>> min(timeit.repeat(lambda: [], repeat=200))
0.06842684745788574

As shown above, using the [] is the fastest. Checking with [] is slightly faster than not [] but they are both faster than checking the length compared to 0 or checking against the empty list.

Leave a Comment