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))
>>> min(timeit.repeat(lambda: [] == [], repeat=200))
>>> min(timeit.repeat(lambda: not [], repeat=200))
>>> min(timeit.repeat(lambda: [], repeat=200))

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