*args & **kwargs
Published by Brayan K
How does print() accept one argument or ten? How does a function pass along whatever it's given to another function? The answer is *args and **kwargs — Python's way of writing functions that accept a flexible, unknown number of inputs.
Part of the free Python course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A star collects the positional arguments
Python's documentation gives the start of print()'s definition as print(*objects, sep=' ', end='\n'). The star in front of objects is what lets it take any number of values. Put a star before a parameter in your own def and that parameter collects the call's positional arguments into one tuple, a sequence like a list that can't be changed. When ordinary parameters come first, it collects the ones they leave over:
def show(*args):
print(type(args), len(args), args)
show()
show("a")
show("a", "b", 3)
# ✅ Expected output:
# <class 'tuple'> 0 ()
# <class 'tuple'> 1 ('a',)
# <class 'tuple'> 3 ('a', 'b', 3)A tuple of one item prints with a comma after it, which Tuples explains. The star is what matters; args is only the usual name, and a name that says what the values are reads better:
def average(*scores):
return sum(scores) / len(scores)
print(average(70, 80))
print(average(55, 65, 90, 70))
# ✅ Expected output:
# 75.0
# 70.0Called with no scores at all, average() gets an empty tuple and stops with ZeroDivisionError: division by zero, the empty-list problem from Lists and Collections, with the same fix: a guard clause.
args is a tuple, so it can't be changed
You can loop over the tuple, index it and pass it to sum(), but the list methods that change a list in place don't exist on it:
def add_all(*numbers):
numbers.append(0)
return sum(numbers)
print(add_all(1, 2))
# ✅ Expected error:
# AttributeError: 'tuple' object has no attribute 'append'To change the values, make a list from them first: values = list(numbers), then work on values.
Two stars collect the keyword arguments
**kwargs does the same for arguments given by name: each name=value in the call becomes a pair in a dictionary, with the name as a string key:
def make_profile(**details):
print(type(details))
for key, value in details.items():
print(key, "=", value)
make_profile(name="Ada", city="London")
# ✅ Expected output:
# <class 'dict'>
# name = Ada
# city = London**details takes only named arguments, so make_profile("Ada") stops with TypeError: make_profile() takes 0 positional arguments but 1 was given. In the same way, *args takes only positional ones: with def total(*nums), the call total(1, 2, start=10) stops with TypeError: total() got an unexpected keyword argument 'start'.
Parameters after *args are keyword-only
A parameter written after *args can only get a value by name, because every positional value goes into the tuple. That's how print()'s sep and end work, and it's easy to forget when calling:
def checkout(*prices, tax=0):
return round(sum(prices) * (1 + tax), 2)
print(checkout(10, 20))
print(checkout(10, 20, tax=0.2))
print(checkout(10, 20, 0.2))
# ✅ Expected output:
# 30
# 36.0
# 30.2The third call has no error: 0.2 was counted as a third price. Without a default, a keyword-only parameter has to be given, by name, in every call:
def checkout(*prices, tax):
return round(sum(prices) * (1 + tax), 2)
print(checkout(10, 20))
# ✅ Expected error:
# TypeError: checkout() missing 1 required keyword-only argument: 'tax'The kinds of parameter in this lesson always come in this order in a def: ordinary ones, then *args, then keyword-only ones, then **kwargs, as in def report(title, *values, sep=", ", **details). Anything after **kwargs, or two single-star parameters, is a SyntaxError, whose wording differs between Python versions. One more kind can come before them all: the parameters before a / are positional-only, so in def f(a, /, b) the a can only be given by position. A bare *, with no name after it, makes the parameters after it keyword-only without collecting anything, so an extra positional argument is an error instead of being swallowed:
def connect(host, *, timeout=10):
return host + ":" + str(timeout)
print(connect("example.org", timeout=5))
print(connect("example.org", 5))
# ✅ Expected output:
# example.org:5
# ✅ Expected error:
# TypeError: connect() takes 1 positional argument but 2 were givenStars in a call spread the values out
In a call, the stars do the opposite of what they do in a def. * spreads a list or tuple into separate positional arguments, and ** spreads a dictionary into keyword arguments, its keys naming the parameters:
def greet(greeting, name):
return greeting + ", " + name + "!"
parts = ["Hello", "Ada"]
print(greet(*parts))
data = {"greeting": "Hi", "name": "Ben"}
print(greet(**data))
nums = [1, 2, 3]
print(nums)
print(*nums, sep="-")
# ✅ Expected output:
# Hello, Ada!
# Hi, Ben!
# [1, 2, 3]
# 1-2-3The last line is print(1, 2, 3, sep="-") written with a star. Forget the star and the whole list arrives as a single argument:
def greet(greeting, name):
return greeting + ", " + name + "!"
parts = ["Hello", "Ada"]
print(greet(parts))
# ✅ Expected error:
# TypeError: greet() missing 1 required positional argument: 'name'greeting got the whole list and name got nothing. One star on a dictionary is a quieter mistake, because going through a dictionary gives its keys:
def greet(greeting, name):
return greeting + ", " + name + "!"
data = {"greeting": "Hi", "name": "Ben"}
print(greet(*data))
# ✅ Expected output:
# greeting, name!With **, every key has to name one of greet's parameters. A key such as "person" stops the call with TypeError: greet() got an unexpected keyword argument 'person'.
Passing arguments on
Collecting with stars in the def and spreading with stars in a call lets a function pass whatever it was given to another function, without knowing what that function takes:
def area(width, height, unit="m"):
return str(width * height) + " " + unit
def logged(func, *args, **kwargs):
print("calling", func.__name__, args, kwargs)
return func(*args, **kwargs)
print(logged(area, 4, 5, unit="cm"))
# ✅ Expected output:
# calling area (4, 5) {'unit': 'cm'}
# 20 cmA function is a value, as Functions showed, so area can be passed in like any other argument, and __name__ is its name. Higher-Order Functions & Function Factories covers passing functions around, and Decorators & Advanced Features builds on this pattern. Stars also work outside calls, to join lists and dictionaries or collect the rest of an unpacking, which Unpacking & Star Expressions covers.
Practice: a total with a discount
Fill the three blanks with the values in the hint lines, in order: let total take any number of prices, spread a list into it, and give the discount by name.
def total(___prices, discount=0):
return sum(prices) - discount
print(total(5, 10, 15))
basket = [4, 6]
print(total(___basket))
print(total(5, 10, ___=3))
# 👉 replace ___ with *
# 👉 replace ___ with *
# 👉 replace ___ with discount
# ✅ Expected output:
# 30
# 10
# 12On your own: an average that can drop the lowest score
Write average(*scores, drop_lowest=False). It returns the average of any number of scores, leaving out the lowest one first when drop_lowest=True, and returns 0 when there's nothing left to average. Remember that scores is a tuple. Check that average(70, 80, 90) gives 80.0, that the same call with drop_lowest=True gives 85.0 and that average() gives 0; then average a list of results with a star. Then compare with this solution:
def average(*scores, drop_lowest=False):
values = list(scores)
if drop_lowest and values:
values.remove(min(values))
if not values:
return 0
return sum(values) / len(values)
print(average(70, 80, 90))
print(average(70, 80, 90, drop_lowest=True))
print(average())
results = [50, 60]
print(average(*results, drop_lowest=True))
# ✅ Expected output:
# 80.0
# 85.0
# 0
# 60.0list(scores) makes a list that remove() can change. The and values check skips the removal when there are no scores, and the guard clause then returns 0 before anything divides by zero.
Practice quiz
Inside def f(*args), what type is args?
- list
- dict
- tuple
- set
Answer: tuple. *args collects the positional arguments into a tuple.
Inside def g(**kwargs), what type is kwargs?
- dict
- tuple
- list
- set
Answer: dict. **kwargs collects the keyword arguments into a dictionary.
def add(*nums): return sum(nums). What does add() return?
- None
- An error
- ()
- 0
Answer: 0. With no arguments, nums is an empty tuple, and sum(()) is 0.
def sub(a, b): return a - b. What does sub(*[10, 3]) return?
- 13
- 7
- [10, 3]
- An error
Answer: 7. The star spreads the list, so a is 10 and b is 3.
def checkout(*prices, tax=0). What does checkout(10, 20, 0.2) do with the 0.2?
- Uses it as the tax
- Raises a TypeError
- Ignores it
- Counts it as a third price
Answer: Counts it as a third price. Every positional argument goes into prices. tax can only be set by name.
Which def line is valid?
- def f(**kwargs, *args):
- def f(a, *args, **kwargs):
- def f(*args, **kwargs, a):
- def f(**kwargs, a):
Answer: def f(a, *args, **kwargs):. **kwargs has to come last. The other three are SyntaxErrors.
def greet(greeting, name), and data = {"greeting": "Hi", "name": "Ben"}. Which call passes "Hi" and "Ben"?
- greet(data)
- greet(*data)
- greet(**data)
- greet(***data)
Answer: greet(**data). ** spreads a dictionary into keyword arguments. One star would pass its keys.
def f(*args): args.append(1). What happens when you call f()?
- It stops with AttributeError: 'tuple' object has no attribute 'append'
- It returns [1]
- args becomes (1,)
- Nothing
Answer: It stops with AttributeError: 'tuple' object has no attribute 'append'. args is a tuple, and a tuple can't be changed.
Continue this course
- Previous: Dictionaries
- Next: Lambda Functions — Write small anonymous functions for sorting, mapping and filtering
- Quick reference: Python cheat sheet › Functions
Frequently asked questions
Is *args the same as taking a list?
Not quite. With def total(*nums) the caller writes the values one by one, total(1, 2, 3), and the function receives a tuple. With def total(nums) the caller builds the list first, total([1, 2, 3]). A star in the call, total(*values), turns a list into the first form.
When should I avoid *args and **kwargs?
When a function always takes the same arguments. Named parameters say what the function needs, and a wrong call gets a clear error instead of being collected without a word. Keep the stars for functions that really take any number of values, like print(), and for functions that pass their arguments on.