mysum is a small Python exercise in function design: accept separate numeric arguments, iterate through them, and return their total without calling the built-in sum. section 1.7
Summing a variable number of numbers
def mysum(*numbers): output = 0 for number in numbers: output += number return output mysum(1, 2, 3) # 6 mysum(10, 20, 30, 40) # 100 mysum(*[1, 2, 3]) # 6 The * parameter collects every positional argument in a tuple. Passing * when calling the function expands a list into separate arguments; passing the list directly would create a one-element tuple containing that list. section 1.8 section 1.7
The same pattern can combine numbers, strings, lists, or tuples when every argument shares a type that supports +. Starting with the first item preserves that type; an empty call returns the empty tuple. section 3.6 section 3.7
A type-preserving version
def mysum(*items): if not items: return items output = items[0] for item in items[1:]: output += item return output mysum(1, 2, 3) # 6 mysum('abc', 'def') # 'abcdef' mysum([1, 2], [3, 4]) # [1, 2, 3, 4] The slice items[1:] skips the initial accumulator. A single argument produces that argument unchanged because the slice is empty. section 3.7 section 3.6
Useful follow-up variations include:
- Add an optional starting value, matching the behavior of sum([1, 2, 3], 4). section 1.11
- Adapt the iteration pattern to calculate averages, word-length statistics, or sums of values convertible to integers. section 1.11
Shows the first-element accumulator after assignment, making the type-preserving implementation easier to trace. section 3.7
Shows the accumulator after subsequent elements are added. section 3.7
