Menu
CoddyTech

Varargs and Keyword Options

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

Gather extra positional arguments with *values and named arguments with **options. Java varargs provides an array of a declared element type; Python *values collects a tuple and **options collects a dictionary. At a call site, * unpacks an iterable into positional arguments, while ** unpacks a mapping whose keys are strings into named arguments. An empty collection contributes no arguments. The function can deliberately accept a limited set of option names or ignore extras when its contract says so.

Java excerpt: class member declarations

// Class member
static int total(int... values) {
    int result = 0;
    for (int value : values) result += value;
    return result;
}

Python

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

Watch the difference

Passing the list itself is not the same as unpacking it. Repeating a keyword, including through **, raises TypeError; it does not overwrite an earlier argument. Java varargs does not provide named option binding.

Practice

Apply this comparison in the task below. Editable files: functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

challenge icon

Challenge

Beginner

Implement scaled_total(*values, **options). Return the sum of integer values times options.get("factor", 1), ignoring other option names. Do not mutate inputs or print. The driver reads integer tokens (possibly none), then a factor, and prints results from an unpacked positional call and a call with unpacked factor options. Python positional extras form a tuple, unlike Java's typed varargs array.

Editable files: functions.py. Keep the provided imports and the required API names. The locked driver.py supplies execution and checks; do not edit it.

Implement the named definitions in the editable modules without input or printing. The driver owns input/output and may call the APIs again on fresh data without producing extra output.

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 Java Developers

Practice on your own: Online Python compiler