Facebooktwitterredditpinterestlinkedintumblr

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

An example could be a list of fruits 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 is 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 faster than checking the length compared to 0 or checking against the empty list.

Tim Miller

Tim has always been obsessed with computers his whole life. After working for 25 years in the computer and electronics field, he now enjoys writing about computers to help others. Most of his time is spent in front of his computer or other technology to continue to learn more. He likes to try new things and keep up with the latest industry trends so he can share them with others.

Leave a Comment