Part 2 of 6 · Chapter 4 of 4

What Counts as Empty, False, or Equal

Python will evaluate almost anything as true or false, including things that are neither. Feed in an empty list, the number zero, and the string that spells the word False, and see which ones the language actually treats as false.

Beginner8 min read

Worth reading first: Ordered Collections, Two Ways


Python will evaluate almost anything as true or false, including things that are neither. Feed in an empty list, the number zero, and the string that spells the word False, and see which ones the language actually treats as false.

What counts as empty

Write if some_list: instead of if len(some_list) > 0: and Python will do exactly what you mean — but only because it treats every empty collection, and the number zero, as false.

bool(value)

>>> bool(0)

False

Only 0, "", [], {}, and None count as false. The string "False" is not empty, so it is true — a common surprise the first time you read a value from user input and check it directly.

A collection that refuses duplicates

A set is an unordered collection that will not hold the same value twice — add a duplicate, and nothing happens, silently.

Terminal
$ >>> tags = ["python", "beginner", "python", "tutorial"]$ >>> set(tags)$ {'python', 'beginner', 'tutorial'}

Turning a list into a set is the fastest way to deduplicate it. Notice the order is not preserved — a set does not remember which item came first, only which items exist.

Testing membership without a loop

Checking whether a value is in a list means Python walks the list from the start until it finds it, or reaches the end. Checking a set is close to instant regardless of size, because a set is built for exactly this question.

Terminal
$ >>> allowed = {"admin", "editor", "viewer"}$ >>> "editor" in allowed$ True

Key takeaways

  • 0, empty strings, empty collections, and None are all falsy. Everything else, including "False" the string, is truthy.
  • A set holds each value at most once — adding a duplicate does nothing, silently.
  • set(some_list) is the fastest way to deduplicate a list, at the cost of losing its order.
  • Membership tests (in) are close to instant on a set, and get slower the longer a list is.