⚡0 XP🔥0

Function Arguments (*args, **kwargs)

Lesson 20 of 33 ⏱ 4 min read ✎ 3 exercises ❓ 5-question quiz ▶ Runs Python

Positional and keyword arguments, default values, the mutable-default trap, variable-length *args and **kwargs, and argument unpacking.

Types of arguments#

Python gives you flexible ways to pass values into functions:

  1. Positional arguments
  2. Keyword arguments
  3. Default parameter values
  4. Variable-length *args
  5. Variable-length keyword **kwargs

1. Positional arguments#

Values are matched to parameters by position (order):

▶ Try it YourselfPython
Ctrl + Enter to run

2. Keyword arguments#

Name the parameter in the call - then order doesn't matter, and the call is easier to read:

▶ Try it YourselfPython
Ctrl + Enter to run
Common Mistake

Positional arguments must come before keyword arguments in a call: introduce(name="Neha", 19, "Ujjain") is a SyntaxError.

3. Default parameter values#

Give a parameter a default; the caller may skip it:

▶ Try it YourselfPython
Ctrl + Enter to run

Parameters with defaults must come after those without:

def f(a=1, b):     # SyntaxError: non-default argument follows default argument

The mutable default trap#

Common Mistake

Never use a list or dict as a default value. The default is created once, when the function is defined, and shared between calls:

def add_item(item, basket=[]):
    basket.append(item)
    return basket

print(add_item("pen"))     # ['pen']
print(add_item("book"))    # ['pen', 'book']  <- surprise!

Use None instead:

def add_item(item, basket=None):
    if basket is None:
        basket = []
    basket.append(item)
    return basket

4. *args - any number of positional arguments#

A parameter starting with * collects all extra positional arguments into a tuple:

▶ Try it YourselfPython
Ctrl + Enter to run

The name args is just a convention - *marks or *numbers work the same. The * is what matters.

5. **kwargs - any number of keyword arguments#

A parameter starting with ** collects extra keyword arguments into a dictionary:

▶ Try it YourselfPython
Ctrl + Enter to run
हिंदी में समझें

*args और **kwargs तब काम आते हैं जब आपको पहले से पता न हो कि function को कितनी values मिलेंगी:

  • *args (एक star) - बिना नाम वाली सारी extra values को एक tuple में इकट्ठा कर देता है। जैसे average(80, 90, 70) → marks = (80, 90, 70)
  • **kwargs (दो star) - नाम वाली (key=value) सारी extra values को एक dictionary में इकट्ठा कर देता है। जैसे print_details(name="Ravi", city="Indore") → {'name': 'Ravi', 'city': 'Indore'}

args और kwargs सिर्फ परंपरागत नाम हैं - असली काम * और ** करते हैं।

Combining everything#

The order of parameters in a definition must be:

def func(positional, default=value, *args, keyword_only, **kwargs):
▶ Try it YourselfPython
Ctrl + Enter to run

Parameters after *args (like delivery above) can only be passed by keyword.

Unpacking arguments in a call#

* and ** also work the other way - spreading a list or dict into separate arguments:

▶ Try it YourselfPython
Ctrl + Enter to run

Summary#

  • Positional arguments match by order; keyword arguments match by name.
  • Default values make parameters optional - put them after required ones.
  • Don't use mutable defaults ([], {}); use None and create inside.
  • *args → tuple of extra positional values; **kwargs → dict of extra keyword values.
  • In calls, *list and **dict unpack values into arguments.

Practice Exercises

Write your code, then press Check. Your program is tested automatically.

1

Total of any number of values

Write total(*nums) that returns the sum of any number of arguments. total() should return 0.

2

Price with default tax

Write final_price(price, tax=18, discount=0) that applies the discount percentage first, then adds tax percentage on the discounted price, and returns the result rounded to 2 decimals.

3

Build a profile

Write make_profile(name, **details) that returns a dictionary with key "name" plus every keyword argument given.

Quick Quiz

Q1.

Given def f(a, b=5):, what is f(2)'s value of b?

Q2.

Which definition is INVALID?

Q3.

Inside a function, what type is args in def f(*args):?

Q4.

Inside a function, what type is kwargs in def f(**kwargs):?

Q5.

What is printed by def f(a, b): print(a, b) called as f(b=1, a=2)?