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
BeginnerImplement 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"}))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for Java Developers
1From Java Classes to Python
Run Python Without a ClassPrinting Text and CommentsBindings, Types, and finalDivision and Numeric TypesIndentation Defines BlocksRecap: A Python Receipt4Iteration and Transformations
Enhanced Loops and rangeIndexes and Map EntriesSentinels and Loop ControlFrom Streams to ComprehensionsRecap: Stable Ranking2Values Beyond Java Primitives
None and Boolean ValuesValue Equality and IdentityTruth Tests Beyond booleanBranches and Value SelectionRecap: Missing or Eligible5Functions Beyond Methods
Functions Outside ClassesDefaults Instead of OverloadsVarargs and Keyword OptionsScope and Callable ObjectsRecap: Pricing Functions3Collections and Object Sharing
Lists and ArrayList HabitsTuples Without Record ClassesDictionaries and Java MapsShared References and CopiesRecap: Inventory Collections6Contracts, Errors, and Modules
Text Input and Exact OutputValueError and TypeErrorModules Versus Utility ClassesAnnotations Are Not Java TypesRecap: Validate a Batch9Project: An Order Processor
Project: Model an OrderProject: Pricing PoliciesPractice on your own: Online Python compiler