liveBook · Manning

Splat operator

As explained in Python Workout, Second Edition

The splat operator is Python's asterisk syntax for collecting multiple function arguments into a parameter or unpacking an iterable into separate function arguments.

Use Python’s splat operator (*) to collect an unknown number of function arguments or unpack an iterable into separate arguments. A parameter such as *numbers receives a tuple, including an empty tuple when no arguments are passed. section 2.7

Apply the operator in these closely related ways:

  • Define flexible functions with *args or another name; iterate over the resulting tuple rather than indexing it when named parameters would be clearer. section 2.7 section 4.7
  • Unpack a list, set, or tuple at the call site: mysum(*[1, 2, 3]) passes three arguments, unlike mysum([1, 2, 3]), which passes one list argument. section 2.7
  • Unpack iterable elements into a set with {*numbers}; choose this idiom deliberately because set(numbers) may be clearer to newcomers. section 5.17

A variadic summing function

def mysum(*numbers): output = 0 for number in numbers: output += number return output mysum(1, 2, 3) # 6 mysum(*[1, 2, 3]) # 6 For a function that combines values with +, a first-element implementation can return an empty tuple for no arguments, use items[0] as the initial value, and iterate over items[1:]. section 2.7 section 4.7

Figure 4.6 After assigning the first element to output (from the Python Tutor)
figure

Trace the first-element accumulator version of mysum as the tuple is assigned and used. section 4.7

How Python Workout, Second Edition covers it

How deep it goes
Explains tuple storage, empty-input behavior, slicing, type errors, and readability tradeoffs, stopping short of broader argument syntax.
Examples
Uses mysum, unique-number set construction, and a Bowl.add_scoops method receiving Scoop objects.
What you can do after
Build flexible functions, unpack iterables at calls, and expand iterable elements into sets.
How it connects
Connects function arguments with tuples, iterables, sequence slicing, lists, sets, and object methods.

Also explained in

Compare how 2 books explain splat operator →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Python Workout, Second Edition. The section links point to the parts of the book it draws on.