How to Check if a List, Dict or Set is Empty in Python as per PEP8

The aim of this how-to-guide🏁 is to demo checking for empty list in Python as per PEP8 (Style Guide) — I know this is trite/repetitive yet it is still counter-intuitive to me when I encounter this in code of others.

Pavol Kutaj
2 min readSep 7, 2023

The way to go is to simply write “if <object>” which in general performs four checks in Python

if <object>:
  1. Null
  2. Empty
  3. False
  4. Zero (0)
  • if it is a collection, it is mainly for emptiness, though
  • l = [0] of course passes the test and is different from l=[]

Again, for sequences, (strings / lists / tuples), use the fact that empty sequences are false

#Yes:

if not seq:
if seq:

#No:

if len(seq):
if not len(seq):

— from PEP8

  • not just sequences, all collections apply, i.e. do this also for dicts and sets
>>> a = {}
>>> if not a: print("empty")
empty

on duck-typing vs “explicit is better than implicit”

  • from stack_overflow_question_53513
  • there is a trade-off between explicitness and type flexibility
  • being explicit means not doing “magical” things.
  • duck typing means relying on general/conventional interfaces → rather than explicitly checking for types → you could argue that conventional interfaces are not magical, right
  • so something like if a == [] is forcing a particular type (() == [] is False).
  • here, general consensus seems to be that duck typing wins out
  • in effect, it is saying that __nonzero__ is the interface for testing emptiness (__bool__ in python 3 → built-in bool())
  • see https://docs.python.org/3/reference/datamodel.html#object.__bool__
>>> a = []
>>> bool(a)
False
>>> a = [1]
>>> bool(a)
True

compare: how things are done in C, also from SO

The canonical way of knowing if an array in C is empty is by dereferencing the first element and seeing if it is null, assuming an array that is nul-terminated. Otherwise, comparing its length to zero is utterly inefficient if the array is of a significant size. Also, typically, you would not allocate memory for an empty array (pointer remains null), so it makes no sense to attempt to get its length. I am not saying that len(a) == 0 is not a good way of doing it, it just does not scream 'C' to me when I see it.

5. sources

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com