*args and **kwargs
So far every function we have written has taken a fixed number of parameters. But what if you do not know in advance how many arguments will be passed in? What if you want a function that can handle one argument or one hundred without rewriting it each time?
That is exactly what *args and **kwargs are for.
*args
*args allows a function to accept any number of
positional arguments. Instead of defining a fixed
number of parameters, the single *args parameter
collects all the positional arguments passed in and packages them
into a tuple inside the function.
The * is what does the work. The word
args is just a convention. You could call it
*numbers or *items and it would work
exactly the same way. But *args is what every
developer expects to see so stick with it.
Without *args a function that adds numbers would need
a fixed number of parameters:
This works for exactly two numbers. But what if you need to add
three? Or ten? With *args the function handles any
number of arguments without any changes:
Because *args is a tuple inside the function we can
loop over it, pass it to other functions or use any tuple operation
on it. This makes it extremely flexible.
**kwargs
**kwargs works the same way but for keyword arguments. Instead of collecting positional arguments into a tuple, it collects keyword arguments into a dictionary where each keyword becomes a key and each value becomes the corresponding value.
Again the ** is what does the work and
kwargs is just a convention. You will see it written
as **kwargs everywhere so keep it consistent.
Because **kwargs is a dictionary inside the function
we can iterate over it using .items() just like any
other dictionary. This makes it perfect for situations where you
want to pass in a flexible set of named options or settings.
Using *args and **kwargs Together
You can use both in the same function. When you do, the order
matters. Regular parameters come first, then *args,
then **kwargs. Python will throw an error if you
mix up the order.
In the example below we create a function that takes a label as
a regular parameter, a set of numbers via *args and
a set of additional details via **kwargs. The function
adds all the numbers together and displays the result alongside
the keyword details.
Time to experiment!
Coding Exercises (VS Code) Instructions:
- Create a file named args_kwargs.py in your part55 folder.
- Complete the tasks and use # comments to explain your answers.
Exercise 1: *args Basic
-
Task: Define a function called
multiply_all()that uses*argsto accept any number of numbers. -
Goal: Inside the function multiply all the numbers
together and return the result. Call the function four times with
a different number of arguments each time. Write a comment explaining
what data type
*argsis inside the function and why that allows you to loop over it.
Exercise 2: *args with a Condition
-
Task: Define a function called
count_above(threshold, *args)that takes a threshold number as the first parameter and any number of additional numbers via*args. -
Goal: Inside the function count how many of the
numbers in
*argsare greater than the threshold and return that count. Call the function with a threshold of5and the numbers1, 3, 7, 9, 2, 8, 4, 6. Write a comment explaining why the threshold must come before*argsin the parameter list.
Exercise 3: **kwargs Basic
-
Task: Define a function called
build_profile()that uses**kwargsto accept any number of keyword arguments. -
Goal: Inside the function print each key and value
in the following format:
name: Eric. Call the function twice with a completely different set of keyword arguments each time to demonstrate its flexibility. Write a comment explaining what data type**kwargsis inside the function.
Exercise 4: *args and **kwargs Together
-
Task: Define a function called
order_summary(order_id, *items, **details)that takes an order ID as a regular parameter, any number of items via*argsand any number of keyword details via**kwargs. -
Goal: Inside the function print the order ID,
list every item ordered and print each detail. Call the function
with an order ID of
1042, items of'pizza', 'pasta', 'tiramisu'and details ofcustomer='Eric', table=5, paid=True. Write a comment explaining the correct order of parameters and what happens if you mix them up.
Exercise 5: Real World *args and **kwargs
-
Task: Define a function called
generate_report(title, *scores, **metadata). -
Goal: Inside the function use
*scoresto calculate the total, average, highest and lowest score. Use**metadatato print any additional information passed in. Call the function with a title of'Q1 Results', scores of78, 92, 55, 88, 74, 96, 61and metadata ofteacher='Ms Smith', subject='Python', term='Spring'. Add a docstring to the function explaining what each parameter does.
Don't Forget to commit and Push!