Python Fundamentals · Collections

List and Dict Comprehensions

Build a list in one readable line. Compare a loop with its comprehension, then add a filter, and build a dictionary the same way.

comprehensions.py

nums = [1, 2, 3, 4, 5, 6]

squares = []
for n in nums:
    squares.append(n * n)

squares_again = [n * n for n in nums]              # the same, in one line
evens = [n for n in nums if n % 2 == 0]            # with a filter
labels = {n: "even" if n % 2 == 0 else "odd" for n in nums[:3]}
print(squares == squares_again, evens, labels)

Step by step

  1. nums is created and points to a new list: [1, 2, 3, 4, 5, 6].
  2. The long way: an empty list, then a loop that appends.
  3. n is created with the value 1.
  4. 1 × 1 = 1 appended.
  5. n changes from 1 to 2.
  6. 4 is added to the end of the list that squares points to.
  7. n changes from 2 to 3.
  8. 9 is added to the end of the list that squares points to.
  9. n changes from 3 to 4.
  10. 16 is added to the end of the list that squares points to.
  11. n changes from 4 to 5.
  12. 25 is added to the end of the list that squares points to.
  13. n changes from 5 to 6.
  14. 36 is added to the end of the list that squares points to.
  15. Python moves to the next item of the loop: for n in nums.
  16. The same list in one line: [expression for item in items].
  17. Add if at the end to keep only some items: the even numbers.
  18. Braces and key: value make a dictionary comprehension.
  19. The comprehension gave exactly the same list as the loop (True), in one line.