sum()
sum() adds up all the numbers in an iterable and gives you back the total.
Used in 60 lessons of the course, from 00.03.
sum(iterable) walks through the items, adds them one by one, and returns the result. It starts at 0, so an empty list gives 0.
You can give it a list, a tuple, or anything you can loop over. It also accepts a second value, start, where the count begins.
The course uses it with a generator expression:
sum(1 for cell in cells if cell.get("outputs"))
Each cell that passes the condition produces a 1, and sum adds them up. That is a way to count how many items match something, without building an intermediate list. You read it from the inside out: first the for with its if, then the sum.
Reach for it when: you need a total of numbers, or a count of how many items meet a condition.
Examples
Common mistake
print(sum(1, 2, 3))
Why: sum() takes a single iterable, not loose numbers. The 2 would be read as start.
How to write it: Put the numbers in a list or tuple: sum([1, 2, 3]).
Common mistake
print(sum(["a", "b"]))
Why: sum() starts at 0 and can't add a number to a string.
How to write it: To join strings use "".join(["a", "b"]).
