Extra Arguments and Unpacking
Lesson 24 of 48 in Coddy's Python for JavaScript Developers course.
Accept a variable number of inputs and expand existing collections into a function call without changing the collections.
JavaScript
function total(...values) {
return values.reduce((sum, value) => sum + value, 0);
}
const numbers = [2, 4, 1];
console.log(total(...numbers));Python
def total(*values):
return sum(values)
numbers = [2, 4, 1]
print(total(*numbers))What changes
Both programs print 7. In a Python definition, *values gathers extra positional arguments into a tuple. In a call, *numbers expands the iterable into separate positional arguments. These two directions resemble JavaScript rest and spread, but JavaScript rest produces an array. Python also supports **options in a definition to gather extra keyword arguments into a dictionary. At a call site, **settings expands a mapping with string keys into keyword arguments. This is not JavaScript object spread: it participates in Python parameter binding rather than creating an object. sum adds a sequence of numbers and returns zero for an empty sequence.
Common mistake
Unpacking does not make duplicate argument bindings legal. A keyword supplied explicitly and again through a dictionary raises TypeError; it does not silently overwrite the first value. Likewise, passing a list without the star passes one list argument rather than several numbers.
Your task
Aggregate variable-length numeric inputs and read an optional setting. The driver demonstrates both unpacking forms and also checks empty positional input.
Challenge
BeginnerImplement 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"}))
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Python for JavaScript Developers
1From JavaScript to Python
Run Your First Python ProgramPrint, Comments, and StringsVariables Without let or constNumbers and ConversionBlocks Use IndentationRecap: Rewrite a Receipt4Iteration and Transformations
for Loops Iterate ValuesIndexes and Dict Iterationwhile, break, and continueComprehensions and SortingRecap: Build a Ranking2Values and Decisions
None, True, and FalseEquality and IdentityTruthiness and Short-CircuitBranches and ExpressionsRecap: Eligibility Rules5Functions and Scope
Define and ReturnPositional and Keyword ArgsExtra Arguments and UnpackingScope, Callbacks, and LambdasRecap: Refactor a Pricing Tool3Collections and References
Lists Instead of ArraysTuples and UnpackingDictionaries and RecordsSets, Aliasing, and CopiesRecap: Clean an Inventory6Reliable Python Programs
Input and Output ContractsExceptions and ValidationModules and the Main GuardReading Type HintsRecap: Validate a Batch9Project: Order Processing
Create the Order ModelAdd Pricing PoliciesPractice on your own: Online Python compiler