9.1. Idiom Sum
9.1.1. Problem
>>> data = [1, 2, 3]
>>>
>>> result = 0
>>> for x in data:
... result += x
>>>
>>> print(result)
6
9.1.2. Solution
>>> data = [1,2,3]
>>> result = sum(data)
>>>
>>> print(result)
6
9.1.3. Multidimensional
>>> DATA = [[1, 2, 3],
... [4, 5, 6],
... [7, 8, 9]]
Iterative version:
>>> result = 0
>>> for row in DATA:
... for value in row:
... result += value
>>>
>>> print(result)
45
Idiomatic version:
>>> result = sum(sum(row) for row in DATA)
>>>
>>> print(result)
45
9.1.4. Gauss Problem
Sum numbers from 1 to 100
Sum numbers from 1 to 100:
1 2 3 ... 97 98 99
0 + 100 = 100
1 + 99 = 100
2 + 98 = 100
3 + 97 = 100
...
49 + 51 = 100
+ 50
We have 50 of such pairs (summing to 100) plus 50 (without pair), therefore result is 5050.
>>> sum(x for x in range(1,101))
5050
9.1.5. Use Case - 1
>>> USERS = [
... {'firstname': 'Alice', 'lastname': 'Apricot', 'age': 30, 'email': 'alice@example.com'},
... {'firstname': 'Bob', 'lastname': 'Banana', 'age': 31, 'email': 'bob@example.com'},
... {'firstname': 'Carol', 'lastname': 'Corn', 'age': 32, 'email': 'carol@example.com'},
... {'firstname': 'Dave', 'lastname': 'Durian', 'age': 33, 'email': 'dave@example.org'},
... {'firstname': 'Eve', 'lastname': 'Elderberry', 'age': 34, 'email': 'eve@example.org'},
... {'firstname': 'Mallory', 'lastname': 'Melon', 'age': 15, 'email': 'mallory@example.net'},
... ]
>>>
>>> sum(user['age'] for user in USERS)
175
9.1.6. Use Case - 2
>>> USERS = [
... ('firstname', 'lastname', 'age'),
... ('Alice', 'Apricot', 30),
... ('Bob', 'Banana', 31),
... ('Carol', 'Corn', 32),
... ('Dave', 'Durian', 33),
... ('Eve', 'Elderberry', 34),
... ('Mallory', 'Melon', 15),
... ]
>>>
>>> sum(user[2] for user in USERS[1:])
175
9.1.7. Use Case - 3
>>> IRIS = [
... ('sepal_length', 'sepal_width', 'petal_length', 'petal_width', 'species'),
... (5.8, 2.7, 5.1, 1.9, 'virginica'),
... (5.1, 3.5, 1.4, 0.2, 'setosa'),
... (5.7, 2.8, 4.1, 1.3, 'versicolor'),
... (6.3, 2.9, 5.6, 1.8, 'virginica'),
... (6.4, 3.2, 4.5, 1.5, 'versicolor'),
... (4.7, 3.2, 1.3, 0.2, 'setosa'),
... (7.0, 3.2, 4.7, 1.4, 'versicolor'),
... (7.6, 3.0, 6.6, 2.1, 'virginica'),
... (4.9, 3.0, 1.4, 0.2, 'setosa'),
... (4.9, 2.5, 4.5, 1.7, 'virginica'),
... ]
Calculation:
>>> sl = sum(row[0] for row in IRIS[1:])
>>> sw = sum(row[1] for row in IRIS[1:])
>>> pl = sum(row[2] for row in IRIS[1:])
>>> pw = sum(row[3] for row in IRIS[1:])
>>> total = sum(sum(values) for *values,species in IRIS[1:])
Result:
>>> print(sl)
58.4
>>>
>>> print(sw)
30.0
>>>
>>> print(pl)
39.199999999999996
>>>
>>> print(pw)
12.3
>>>
>>> print(total)
139.9
9.1.8. Assignments
# %% About
# - Name: Idiom Sum Impl
# - Difficulty: easy
# - Lines: 4
# - Minutes: 3
# %% License
# - Copyright 2025, Matt Harasymczuk <matt@python3.info>
# - This code can be used only for learning by humans
# - This code cannot be used for teaching others
# - This code cannot be used for teaching LLMs and AI algorithms
# - This code cannot be used in commercial or proprietary products
# - This code cannot be distributed in any form
# - This code cannot be changed in any form outside of training course
# - This code cannot have its license changed
# - If you use this code in your product, you must open-source it under GPLv2
# - Exception can be granted only by the author
# %% English
# 1. Write own implementation of a built-in `sum()` function
# 2. Define function `mysum` with
# parameter `iterable: list[int|float]`
# return `int|float`
# 3. Don't validate arguments and assume, that user will
# always pass valid type of arguments
# 4. Do not use built-in function `sum()`
# 5. Run doctests - all must succeed
# %% Polish
# 1. Zaimplementuj własne rozwiązanie wbudowanej funkcji `sum()`
# 2. Zdefiniuj funkcję `mysum` z parametrami:
# parametr `iterable: list[int|float]`
# return `int|float`
# 3. Nie waliduj argumentów i przyjmij, że użytkownik:
# zawsze poda argumenty poprawnych typów
# 4. Nie używaj wbudowanej funkcji `sum()`
# 5. Uruchom doctesty - wszystkie muszą się powieść
# %% Doctests
"""
>>> import sys; sys.tracebacklimit = 0
>>> assert sys.version_info >= (3, 9), \
'Python 3.9+ required'
>>> from inspect import isfunction
>>> assert isfunction(mysum)
>>> mysum([1])
1
>>> mysum([0])
0
>>> mysum([1, 0, 2])
3
>>> mysum([-1, 2, 0])
1
>>> mysum([0, 0, 0])
0
"""
# %% Run
# - PyCharm: right-click in the editor and `Run Doctest in ...`
# - PyCharm: keyboard shortcut `Control + Shift + F10`
# - Terminal: `python -m doctest -v myfile.py`
# %% Imports
# %% Types
from typing import Callable
mysum: Callable[[list[int|float]], int|float]
# %% Data
# %% Result
def mysum(iterable):
...