Python - built-in sum function vs. for loop


Python Clean Code Tip:

Use sum to sum the values of all elements inside an iterable instead of a for loop.

Why?

  1. Don't re-invent the wheel!
  2. sum is much faster

👇

transactions = [10.0, -5.21, 101.32, 1.11, -0.38]

# without sum
balance = 0


for transaction in transactions:
    balance += transaction


# with sum
balance = sum(transactions)