Skip to content
Codewilds

Lesson 10 of 34 · Functions

Python Function Arguments: Defaults, *args and **kwargs

medium20 XP3 min read

Python functions are remarkably flexible about how they receive arguments. Parameters can have default values, callers can pass arguments by name, and a single function can accept any number of arguments with *args and **kwargs. Understanding these tools also helps you read the signatures of built-ins such as print() and sorted().

Positional and keyword arguments

By default, arguments are matched to parameters by position. You can also pass them by name — as keyword arguments — in any order:

def describe(name, job):
    return f"{name} the {job}"


print(describe("Ada", "engineer"))          # Ada the engineer
print(describe(job="wizard", name="Merl"))  # Merl the wizard

Keyword arguments make calls self-explanatory, especially for booleans and numbers. When you mix both styles, positional arguments must come first.

Default parameter values

A parameter with a default value becomes optional:

def roll(sides=6, times=1):
    return f"Rolling {times}d{sides}"


print(roll())          # Rolling 1d6
print(roll(20))        # Rolling 1d20
print(roll(times=3))   # Rolling 3d6

Parameters with defaults must come after those without. You've already used defaults: print() has sep=" " and end="\n", so print("a", "b", sep="-") prints a-b.

The mutable default trap

Default values are created once, when the function is defined — not on every call. A mutable default such as a list is therefore shared between calls:

def add_loot(item, bag=[]):  # don't do this!
    bag.append(item)
    return bag


print(add_loot("gem"))    # ['gem']
print(add_loot("sword"))  # ['gem', 'sword']  <- the old item is still there!

The standard fix is to use None as the default and create a fresh list inside:

def add_loot(item, bag=None):
    if bag is None:
        bag = []
    bag.append(item)
    return bag

*args: any number of positional arguments

A parameter prefixed with * collects all extra positional arguments into a tuple (an unchangeable sequence — Chapter 3 covers tuples):

def total_damage(*hits):
    return sum(hits)


print(total_damage(5, 12, 8))  # 25
print(total_damage())          # 0

The name args is just a convention; *hits reads better here.

**kwargs: any number of keyword arguments

A parameter prefixed with ** collects extra keyword arguments into a dictionary of names and values (Chapter 4 covers dictionaries in depth). Loop over the pairs with .items():

def show_options(**options):
    for key, value in options.items():
        print(f"{key} -> {value}")


show_options(volume=7, music=True)
# volume -> 7
# music -> True

Keyword-only parameters

Parameters that come after *args — or after a bare * — can only be passed by keyword. This keeps calls readable:

def connect(host, *, timeout=10):
    return f"{host} (timeout {timeout}s)"


connect("db", timeout=5)  # OK
connect("db", 5)          # TypeError: takes 1 positional argument but 2 were given

The full order of a signature is: regular parameters, *args, keyword-only parameters, **kwargs.

Unpacking arguments when calling

* and ** also work in the other direction, spreading a sequence or dictionary into separate arguments: print(*[1, 2, 3]) prints 1 2 3.

Common mistakes

  • Mutable defaults such as [] or {} — use None instead.
  • A positional argument after a keyword argument: describe(name="Ada", "engineer") is a SyntaxError.
  • Misspelled keywords: roll(side=20) raises TypeError: roll() got an unexpected keyword argument 'side'.
  • Passing the same value twice: describe("Ada", name="Bo") raises TypeError: ... got multiple values for argument 'name'.

Assignment

Write three functions:

  1. greet(name, greeting="Hello", punctuation="!") returns "<greeting>, <name><punctuation>".
  2. average(*numbers) returns the average of any number of arguments as a float, or 0.0 when called with none.
  3. format_stats(name, **stats) returns the name followed by a colon, then each stat as key=value in the order it was passed. With no stats it returns just "<name>:".
greet("Ada")                        # "Hello, Ada!"
greet("Bo", "Hi", punctuation="?")  # "Hi, Bo?"
average(2, 4, 9)                    # 5.0
average()                           # 0.0
format_stats("Ada", hp=30, mp=12)   # "Ada: hp=30 mp=12"
format_stats("Bo")                  # "Bo:"

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Function parameters in other languages

Need a quick reminder? The Python cheat sheet has every topic of Learn Python on one page.

Lesson last updated on .

Write code ↓
Python+20 XP

Lesson 10 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Python course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.