Stop 04 · FunctionsTopics · 3/8

Default & Keyword Arguments

Part of the Python Roadmap

In short

Good functions are easy to call. Defaults let callers skip options they don't care about, and keyword arguments make calls readable months later, when nobody remembers what the third parameter was.

Default values make parameters optional, and keyword arguments let callers name what they are passing, which makes calls clearer. Never use a mutable value like [] as a default, because it is shared between calls.

The jaadu leans on a roadside chai stall counter, holding up one finger while the chaiwala pours steaming tea from a height into a small glass.

Think of it like this

Ordering "the usual" at a chai tapri

The chaiwala's default is cutting chai, regular sugar, no elaichi. Say "one chai" and that's what you get. Want a change? You say it by name: "one chai, sugar less". You don't list every option in a fixed order; you name only what's different. That's defaults plus keyword arguments.

Watch it happen

The mutable default trap

basket=[]

  • The empty list is created once, when def runs
  • Every call without basket shares that same list
  • add_item("rice") gives ['rice']
  • add_item("dal") gives ['rice', 'dal']. Surprise!

basket=None

  • None is a safe, unchangeable default
  • Inside: if basket is None: basket = []
  • Each call gets its own fresh list
  • add_item("dal") gives ['dal'] as expected

Never use a list, dict or set as a default value. Use None and create the object inside the function.

The big ideas

What you need to know

Defaults make parameters optional

def book_ticket(name, seat_class="Sleeper"): lets callers leave seat_class out. Parameters with defaults must come after those without.

Keyword arguments name the value

book_ticket("Ankit", meal=True) is self-explaining. Keywords can come in any order, but always after positional arguments.

Defaults are evaluated once

The default value is created when def runs, not on every call. That's harmless for numbers and strings, dangerous for lists and dicts.

Keyword-only parameters

Parameters after a bare * must be passed by name: def pay(amount, *, upi_id). It prevents mix-ups in calls with many options.

See it in code

Walk through the code

python
1def book_ticket(name, seat_class="Sleeper", meal=False):2    meal_text = "with meal" if meal else "no meal"3    return f"{name}: {seat_class}, {meal_text}"4 5 6print(book_ticket("Ankit"))                      # Ankit: Sleeper, no meal7print(book_ticket("Ankit", "3AC"))               # Ankit: 3AC, no meal8print(book_ticket("Ankit", meal=True))           # Ankit: Sleeper, with meal9print(book_ticket(meal=True, seat_class="2AC", name="Ankit"))10 11 12def add_item(item, basket=None):13    if basket is None:14        basket = []15    basket.append(item)16    return basket17 18 19print(add_item("rice"))   # ['rice']20print(add_item("dal"))    # ['dal'], a fresh list each call

1/5name is required. seat_class and meal have defaults, so they're optional.

One function called four ways, and the safe pattern for a list default.

Save yourself the pain

Common mistakes

Oops

def add_item(item, basket=[]): and seeing items from earlier calls appear.

Do this instead

Use basket=None and create the list inside with if basket is None: basket = [].

Oops

def greet(greeting="Hi", name): and getting a SyntaxError.

Do this instead

Required parameters come first: def greet(name, greeting="Hi"):.

Oops

Calling book_ticket(meal=True, "Ankit").

Do this instead

Positional arguments must come before keyword arguments: book_ticket("Ankit", meal=True).

Your mission

A flexible pizza order

~20 min

Quick check

def f(a, b=2, c=3): return a + b + c. What does f(1, c=10) return?

Go deeper

  1. 1Write a greet(name, greeting='Namaste') function and call it both ways.
  2. 2Call a function using keyword arguments in a different order.
  3. 3Use None as the default and create a new list inside the function instead of using [].

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge