How do I check if a list is empty?


For example, if passed the following:

a = []

How do I check to see if a is empty?

11/18/2018 11:13:03 AM

Accepted Answer

if not a:
  print("List is empty")

Using the implicit booleanness of the empty list is quite pythonic.

5/2/2019 4:50:18 PM

The pythonic way to do it is from the PEP 8 style guide (where Yes means “recommended” and No means “not recommended”):

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):

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow