Big O: Counting the Work

Count how many steps a single loop and a nested loop take for the same list. One grows with n, the other with n × n.

Python · intermediate · 7 min · 43 steps · free

What you'll learn

big_o.py

def count_items(items):
    steps = 0
    for a in items:
        steps += 1
    return steps

def count_pairs(items):
    steps = 0
    for a in items:
        for b in items:
            steps += 1
    return steps

data = [4, 8, 15]
print('linear:', count_items(data))
print('quadratic:', count_pairs(data))

Step by step

  1. Python defines the function count_items(). Its body does not run yet: it runs each time the function is called.
  2. Python defines the function count_pairs(). Its body does not run yet: it runs each time the function is called.
  3. data is created and points to a new list: [4, 8, 15].
  4. count_items goes over the list once: one step per item.
  5. steps is created with the value 0.
  6. a is created with the value 4.
  7. steps changes from 0 to 1.
  8. a changes from 4 to 8.
  9. steps changes from 1 to 2.
  10. a changes from 8 to 15.
  11. 3 items, 3 steps. With 1,000 items it would be 1,000 steps: the work grows in a straight line. That is O(n).
  12. Python moves to the next item of the loop: for a in items.
  13. The function returns steps.
  14. count_items() has finished, so its names are gone. It prints linear: 3.
  15. count_pairs has a loop inside a loop: for every a, it goes over every b.
  16. steps is created with the value 0.
  17. a is created with the value 4.
  18. b is created with the value 4.
  19. steps changes from 0 to 1.
  20. b changes from 4 to 8.
  21. steps changes from 1 to 2.
  22. b changes from 8 to 15.
  23. steps changes from 2 to 3.
  24. Python moves to the next item of the loop: for b in items.
  25. The outer loop moves to 8, and the inner loop starts again from the beginning.
  26. b changes from 15 to 4.
  27. steps changes from 3 to 4.
  28. b changes from 4 to 8.
  29. steps changes from 4 to 5.
  30. b changes from 8 to 15.
  31. steps changes from 5 to 6.
  32. Python moves to the next item of the loop: for b in items.
  33. a changes from 8 to 15.
  34. b changes from 15 to 4.
  35. steps changes from 6 to 7.
  36. b changes from 4 to 8.
  37. steps changes from 7 to 8.
  38. b changes from 8 to 15.
  39. steps changes from 8 to 9.
  40. Python moves to the next item of the loop: for b in items.
  41. Python moves to the next item of the loop: for a in items.
  42. The function returns steps.
  43. 9 steps for 3 items. With 1,000 items it would be 1,000,000. Nested loops over the same data are O(n²).

Common mistakes

Best practices

Key takeaways

Check yourself

Doubling n makes an O(n²) algorithm do how much more work?

Answer: 4×. (2n)² = 4n².

Which is faster for big inputs?

Answer: O(n)

More in Complexity and Searching