2

Yesterday during a code review, I learned that once a list has elements you can write:

fruits = []
fruits.append("Apple")
fruits.append("Orange")
fruits.append("Grapes")

if fruits:
    # do something with list

It's a simple way to determine if the list is empty or not.

Questions:

  1. Is this behavior documented in the Python Docs? I've searched for myself, but unable to find any explanation.

  2. At first glance it might seem fruits is a boolean in the if statement. What is the internal explanation? Is it testing the if len(fruits) > 0? In other words, what exactly is going on internally that allows someone to write if fruits: despite the fact fruits is a list?

  • 6
    https://docs.python.org/3/library/stdtypes.html#truth-value-testing – jonrsharpe Jun 03 '18 at 16:45
  • Using truthiness is the correct way to check if a sequence is empty. In particular, [PEP8](https://www.python.org/dev/peps/pep-0008/#programming-recommendations) indicates that using `len` is not recommended. – Olivier Melançon Jun 03 '18 at 16:49

0 Answers0