Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

Variadic positional parameter `*items`

In a function definition, `*items` collects leftover positional arguments into a tuple. At a call site, `*values` does the reverse: it passes the elements of an iterable as separate positional arguments.

Version: Python 3.12

Syntax

def macro_bullet(title, *items, marker="-"):
    ...

In Python 3.12, a variadic positional parameter *items collects zero or more positional arguments. In def macro_bullet(title, *items, marker="-"):, the first positional argument fills title, and the rest form the tuple items in the order they were passed. If there are no extra arguments, items is (). The name items is your choice; args is common.

An ordinary parameter after *items, such as marker, is keyword-only: pass it as marker="+". Passing items=... does not bind the tuple items: the call raises TypeError unless the function accepts that keyword through **kwargs, which collects extra keyword arguments in a separate dictionary. A bare * marks the start of keyword-only parameters without collecting positional arguments.

In the call macro_bullet("Plan", *values), the star unpacks the iterable values into separate positional arguments. Without the star, values is passed as one argument, even if it is a list. The star collects arguments in the definition and unpacks them at the call site.

Examples

def macro_bullet(title, *items, marker="-"):
    return title, items, marker

values = [10, 20]
print(macro_bullet("Plan"))
print(macro_bullet("Plan", values))
print(macro_bullet("Plan", 10, 20, marker="+"))
print(macro_bullet("Plan", *values, marker="+"))

Result

('Plan', (), '-')
('Plan', ([10, 20],), '-')
('Plan', (10, 20), '+')
('Plan', (10, 20), '+')

The first line shows an empty tuple; the second shows a tuple containing one list. The last two lines match because unpacking `values` passes the same numbers as writing them separately. Both calls pass `marker` by keyword.

Related lessons

  • Python · Lesson 34 · Advanced · Version: 5

Sources