Menu
CoddyTech

Varargs and Call Unpacking

Lesson 24 of 48 in Coddy's Python for Lua Developers course.

Lua varargs are accessed through ... and can be expanded in the final position of some expression lists. Python collects extra positional arguments into a tuple with *values and keyword arguments into a dictionary with **options. At a call, * expands a sequence and ** expands string-keyed keyword arguments. Python does not use Lua multiple-result adjustment rules. Duplicate keyword names or incompatible parameter bindings raise errors rather than quietly dropping values.

Lua example

local function total(factor, ...)
    local result = 0
    for _, n in ipairs({...}) do result = result + n end
    return result * factor
end
print(total(2, unpack({2, 3})))

Python

def total(*values, **options):
    return sum(values) * options.get("factor", 1)
print(total(*[2, 3], **{"factor": 2}))

Porting trap

Unpacking expands one level, not nested lists recursively. Use explicit flattening logic for nested data.

Implement the specified API in the editable Python files. The locked driver.py runs the program and supplies input/output. Keep its imports and names unchanged.

challenge icon

Challenge

Beginner

Implement scaled_total(*values, **options). All values are integers. Return their sum multiplied by options.get("factor", 1). Ignore other option names. Do not mutate collections or print. The driver reads a line of integer tokens (possibly empty) and a factor on the next line. It prints a call with only unpacked values, then a call with unpacked values and a dictionary containing the factor.

Your function definitions go in functions.py. The locked driver.py imports them and handles the supplied input/output and checks. You do not need to edit the driver.

Try it yourself

from functions import scaled_total

values = [int(part) for part in input().split()]
factor = int(input())
print(scaled_total(*values))
print(scaled_total(*values, **{"factor": factor, "note": "ignored"}))
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Python for Lua Developers

Practice on your own: Online Python compiler