liveBook · Manning

Mysum

As explained in Python Workout: 50 ten-minute exercises

mysum is a book-specific function intended to accept separate numeric arguments and return their sum.

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
Figure 3.6 After assigning the first element to output (from the Python Tutor)

Shows the first-element accumulator after assignment, making the type-preserving implementation easier to trace. section 3.7

Figure 3.7 After adding elements to output (from the Python Tutor)

Shows the accumulator after subsequent elements are added. section 3.7

How Python Workout: 50 ten-minute exercises covers it

How deep it goes
Builds two implementations, explaining tuple collection, iterable expansion, slicing, empty inputs, and type-preserving accumulation.
Examples
Uses numeric totals, list unpacking, string concatenation, list concatenation, tuple handling, and follow-up statistics exercises.
What it assumes
Assumes familiarity with Python functions and iteration while reinforcing parameter flexibility, tuples, slices, and sequence behavior.
What you can do after
Build it from scratch with *args, apply argument unpacking, and adapt accumulation to compatible numeric or sequence values.
How it connects
Connects variadic functions with tuples, argument unpacking, slicing, sequence types, and the + operator.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout: 50 ten-minute exercises. The section links point to the parts of the book it draws on.