*args and **kwargs
Normally a function call has to supply the right number of arguments.
Sometimes, though, you can't tell in advance how many will be passed.
That is the problem *args and **kwargs solve: they let a function accept an unknown number of arguments.
Arbitrary Arguments - *args
When you can't predict how many arguments a function will get, put a * in front of the parameter name.
The function then receives the arguments as a tuple and can reach each item by its position.
Python documentation often abbreviates Arbitrary Arguments to *args.
Example
Accepting any number of arguments with *args:
*kids to accept any number of arguments.
Print the third child. Call it with "Emil", "Tobias", "Linus".
Output: complete Python program
def my_function(*kids):
print("The youngest child is " + kids[2])
my_function("Emil", "Tobias", "Linus")
What is *args?
A function with a *args parameter can take as many positional arguments as the caller wants to send.
All of them end up in args, which is a tuple inside the function:
Example
Reading single arguments out of *args:
*args and print the type, first, second, and all arguments.
Call it with "Emil", "Tobias", "Linus".
Output: complete Python program
def my_function(*args):
print("Type:", type(args))
print("First argument:", args[0])
print("Second argument:", args[1])
print("All arguments:", args)
my_function("Emil", "Tobias", "Linus")
Using *args with Regular Arguments
Regular parameters and *args can appear side by side.
The regular ones have to be listed first.
Here greeting takes the value "Hello", and names collects all the remaining values.
Example
greeting and *names.
Print the greeting with each name. Call with "Hello", "Emil", "Tobias", "Linus".
Output: complete Python program
def my_function(greeting, *names):
for name in names:
print(greeting, name)
my_function("Hello", "Emil", "Tobias", "Linus")
Practical Example with *args
Flexible functions are where *args really helps:
Example
Adding up however many values are passed:
*numbers that calculates the sum of any number of values.
Test with (1,2,3), (10,20,30,40), and (5).
Output: complete Python program
def my_function(*numbers):
total = 0
for num in numbers:
total += num
return total
print(my_function(1, 2, 3))
print(my_function(10, 20, 30, 40))
print(my_function(5))
Example
Looking for the largest value:
*numbers that finds the maximum value.
Return None for empty input. Test with (3, 7, 2, 9, 1).
Output: complete Python program
def my_function(*numbers):
if len(numbers) == 0:
return None
max_num = numbers[0]
for num in numbers:
if num > max_num:
max_num = num
return max_num
print(my_function(3, 7, 2, 9, 1))
Arbitrary Keyword Arguments - **kwargs
When you can't predict how many keyword arguments a function will get, put two asterisks ** in front of the parameter name.
The function then receives them as a dictionary and can look up each item by its key.
Python documentation often abbreviates Arbitrary Keyword Arguments to **kwargs.
Example
Accepting any number of keyword arguments with **kwargs:
**kid to accept keyword arguments.
Print the last name. Call with fname="Tobias", lname="Refsnes".
Output: complete Python program
def my_function(**kid):
print("His last name is " + kid["lname"])
my_function(fname = "Tobias", lname = "Refsnes")
What is **kwargs?
A function with a **kwargs parameter can take as many keyword arguments as the caller wants to send.
All of them end up in kwargs, which is a dictionary inside the function:
Example
Reading values out of **kwargs:
**myvar and print the type, name, age, and all data.
Call with name="Tobias", age=30, city="Bergen".
Output: complete Python program
def my_function(**myvar):
print("Type:", type(myvar))
print("Name:", myvar["name"])
print("Age:", myvar["age"])
print("All data:", myvar)
my_function(name = "Tobias", age = 30, city = "Bergen")
Using **kwargs with Regular Arguments
Regular parameters and **kwargs work together as well.
Here too, the regular ones are listed first:
Example
username and **details.
Print the username and all additional details. Call with "emil123" and extra keyword args.
Output: complete Python program
def my_function(username, **details):
print("Username:", username)
print("Additional details:")
for key, value in details.items():
print(" " + key + ":", value)
my_function("emil123", age = 25, city = "Oslo", hobby = "coding")
Combining *args and **kwargs
One function can have both *args and **kwargs.
List the parameters in this order:
- regular parameters
- *args
- **kwargs
Example
title, *args, and **kwargs.
Print all three. Call with mixed positional and keyword arguments.
Output: complete Python program
def my_function(title, *args, **kwargs):
print("Title:", title)
print("Positional arguments:", args)
print("Keyword arguments:", kwargs)
my_function("User Info", "Emil", "Tobias", age = 25, city = "Oslo")
Unpacking Arguments
You can also write * and ** in a function call. There they unpack (expand) a list or dictionary into individual arguments.
Remember: In a definition, * and ** collect arguments. In a call, they unpack them.
Example
Turning a list into separate arguments with *:
* to unpack a list [1, 2, 3] into the function call.
Output: complete Python program
def my_function(a, b, c):
return a + b + c
numbers = [1, 2, 3]
result = my_function(*numbers) # Same as: my_function(1, 2, 3)
print(result)
Example
Turning a dictionary into keyword arguments with **:
fname and lname and prints a greeting.
Use ** to unpack a dictionary into the function call.
Output: complete Python program
def my_function(fname, lname):
print("Hello", fname, lname)
person = {"fname": "Emil", "lname": "Refsnes"}
my_function(**person) # Same as: my_function(fname="Emil", lname="Refsnes")