Tutorials Python Python *args and **kwargs
Ch 46 / 58
Python Intermediate 12 min read Chapter 46 of 58

Python *args & **kwargs

*args and **kwargs are Python's mechanism for writing functions that accept a variable number of arguments. They're everywhere — in decorators, class constructors, API wrappers, and utility functions. Beyond the function definition, the unpacking operator (* and **) can also be used at call sites to spread iterables and dicts into function arguments, and in assignment to unpack sequences. This chapter covers all the patterns: *args, **kwargs, mixing parameter types, positional-only and keyword-only parameters, and argument forwarding.

What you'll learn in this chapter
*args — variable positional arguments (tuple)
**kwargs — variable keyword arguments (dict)
Correct parameter order in function definitions
Unpacking with * and ** at call sites
Positional-only (/) and keyword-only (*) parameters
Argument forwarding and real-world patterns
Advertisement

*args — Variable Positional Arguments

*args in a function definition collects all extra positional arguments into a tuple. The name args is a convention — the * is what matters. Use it when a function should accept any number of positional arguments.

Python — args_tutorial.py
# ── *args — any number of positional arguments ────────
def total(*numbers):              # 'numbers' is a TUPLE
    print(type(numbers))           # <class 'tuple'>
    return sum(numbers)

print(total(1, 2, 3))           # 6
print(total(10, 20))             # 30
print(total())                    # 0 — no args is fine

# ── Mix with regular params ───────────────────────────
def greet(greeting, *names):
    for name in names:
        print(f"{greeting}, {name}!")

greet("Hello", "Alice", "Bob", "Carol")
# Hello, Alice!
# Hello, Bob!
# Hello, Carol!

# ── Iterate over args ─────────────────────────────────
def show_types(*values):
    for v in values:
        print(f"{v!r} → {type(v).__name__}")

show_types(1, "hello", True, [1,2])
# 1 → int
# 'hello' → str
# True → bool
# [1, 2] → list

# ── *args must come AFTER positional params ───────────
def power(base, exp, *mods):      # base and exp are required
    result = base ** exp
    for m in mods:
        result %= m
    return result

print(power(2, 10))             # 1024   — no mods
print(power(2, 10, 100))         # 24     — 1024 % 100

**kwargs — Variable Keyword Arguments

**kwargs collects all extra keyword arguments into a dict. The name kwargs is convention; the ** is what matters. Use it when a function should accept any named parameters — common in builders, configuration, and API wrappers.

Python — kwargs_tutorial.py
# ── **kwargs — any number of keyword arguments ────────
def describe(**info):              # 'info' is a DICT
    print(type(info))              # <class 'dict'>
    for key, val in info.items():
        print(f"  {key}: {val}")

describe(name="Alice", age=25, city="Vadodara")
#   name: Alice
#   age: 25
#   city: Vadodara

describe()                         # empty dict — ok!

# ── Access specific keys ──────────────────────────────
def create_user(**fields):
    name  = fields.get("name", "Anonymous")
    email = fields.get("email", "")
    role  = fields.get("role",  "user")
    print(f"Creating {role}: {name} <{email}>")

create_user(name="Bob", email="bob@k2.com")
create_user(name="Admin", role="superuser", email="a@k2.com")

# ── Mix with regular params and *args ─────────────────
def log(level, *messages, **context):
    print(f"[{level.upper()}] {' '.join(str(m) for m in messages)}")
    if context:
        print(f"  context: {context}")

log("info", "Server started")
log("error", "DB failed", "retry 3", host="db01", port=5432)
# [ERROR] DB failed retry 3
#   context: {'host': 'db01', 'port': 5432}

Correct Parameter Order

Python enforces a specific order for parameter types in function definitions. Violating this order is a SyntaxError. The full 5-level order from left to right:

Required parameter order — def func(1, 2, 3, 4, 5)
1
Positional / regular
Required parameters with no default value. Must be passed by caller.
def func(x, y): ... ← x and y required
2
Default values
Optional parameters with default values. Must come after required params.
def func(x, y=10): ... ← y is optional
3
*args
Captures extra positional arguments as a tuple. Only one allowed.
def func(x, *extras): ... ← extras is tuple
4
Keyword-only params
Parameters after *args (or bare *) must be passed as keyword=value.
def func(*args, sep=","): ... ← sep is keyword-only
5
**kwargs
Captures extra keyword arguments as a dict. Must be last. Only one allowed.
def func(**kw): ... ← kw is dict, always last
Python — parameter_order.py
# Full parameter order demonstration
def full_sig(pos1, pos2, default1="A", default2="B",
              *args, kw_only1, kw_only2="Z", **kwargs):
    print(f"pos:      {pos1}, {pos2}")
    print(f"defaults: {default1}, {default2}")
    print(f"args:     {args}")
    print(f"kw_only1: {kw_only1}")
    print(f"kw_only2: {kw_only2}")
    print(f"kwargs:   {kwargs}")

full_sig(1, 2, "X", "Y", 10, 20, kw_only1="K", extra="E")
# pos:      1, 2
# defaults: X, Y
# args:     (10, 20)
# kw_only1: K
# kw_only2: Z
# kwargs:   {'extra': 'E'}

# ── Common real-world signatures ─────────────────────
def any_function(*args, **kwargs): pass  # accept literally anything
def pos_and_kw(x, y, **options): pass   # required + options dict
def multi_pos(*items, sep=", "): pass    # items + keyword-only sep
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Unpacking with * and ** at Call Sites

The * and ** operators work in reverse when calling functions — they spread an iterable or dict into individual arguments. They can also unpack in assignments, list/dict literals, and comprehensions.

* unpacking — spread iterable into function arguments
nums = [10, 20, 30] ← list
▼
*nums unpacks the list
func(*nums) ≡ func(10, 20, 30)
▼
function receives 3 positional arguments
func receives: a=10, b=20, c=30
Python — unpacking.py
# ── * unpacking at call site ──────────────────────────
def add(a, b, c): return a + b + c

nums = [1, 2, 3]
print(add(*nums))               # 6  ← same as add(1, 2, 3)
print(add(*(10, 20, 30)))       # 60 ← unpack tuple

# Built-in functions
print(max(*[5, 1, 9, 3]))       # 9
print(min(*range(5)))            # 0

# ── ** unpacking at call site ─────────────────────────
def connect(host, port, timeout=30):
    print(f"Connect {host}:{port} t={timeout}")

config = {"host": "db01", "port": 5432}
connect(**config)                  # Connect db01:5432 t=30
connect(**config, timeout=10)     # override timeout

# ── Use in list/dict literals ─────────────────────────
a    = [1, 2, 3]
b    = [4, 5, 6]
print([*a, *b])                   # [1, 2, 3, 4, 5, 6]
print({*a, *b})                   # {1, 2, 3, 4, 5, 6} (set)

d1 = {"a": 1}
d2 = {"b": 2}
print({**d1, **d2})               # {"a": 1, "b": 2} — merge dicts
print({**d1, **d2, "c": 3})      # {"a": 1, "b": 2, "c": 3}

# ── Unpacking in assignment ───────────────────────────
first, *rest = [1, 2, 3, 4, 5]
print(first)                      # 1
print(rest)                       # [2, 3, 4, 5]

head, *middle, tail = range(6)
print(head, middle, tail)         # 0 [1, 2, 3, 4] 5

Positional-Only (/) and Keyword-Only (*) Parameters

Python 3.8+ introduced / and bare * as parameter separators to enforce how arguments are passed — giving API designers fine-grained control over calling conventions.

Python — pos_only_kw_only.py
# ── / — positional-only params (Python 3.8+) ─────────
def pos_only(x, y, /):           # x and y MUST be positional
    return x + y

pos_only(1, 2)                    # ✅ ok
# pos_only(x=1, y=2)  → TypeError: x is positional-only

# ── * — keyword-only params ───────────────────────────
def kw_only(*, width, height):    # width and height MUST be kwargs
    return width * height

kw_only(width=5, height=10)       # ✅ 50
# kw_only(5, 10)  → TypeError: takes 0 positional arguments

# ── Combine / and * ───────────────────────────────────
def mixed(pos_only, /, normal, *, kw_only):
    print(pos_only, normal, kw_only)

mixed(1, 2, kw_only=3)            # ✅ 1 2 3
mixed(1, normal=2, kw_only=3)    # ✅ also ok

# ── Why use keyword-only? ─────────────────────────────
# Forces clarity — caller can't accidentally pass wrong argument
def sort_data(data, *, reverse=False, key=None):
    return sorted(data, reverse=reverse, key=key)

# sort_data([3,1,2], True) would be wrong — no such call!
# sort_data([3,1,2], reverse=True)  ← must be explicit
print(sort_data([3,1,2], reverse=True))  # [3, 2, 1]

Argument Forwarding — Passing *args/**kwargs Through

A function can collect all its arguments with *args, **kwargs and forward them to another function using the unpacking operators. This pattern is essential for decorators, wrappers, and proxy functions.

Python — argument_forwarding.py
import functools

# ── Decorator forwarding all arguments ───────────────
def debug(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):      # collect everything
        print(f"Calling {func.__name__}")
        result = func(*args, **kwargs)  # forward everything
        print(f"→ {result!r}")
        return result
    return wrapper

@debug
def multiply(a, b, factor=1):
    return a * b * factor

multiply(3, 4, factor=2)          # Calling multiply → 24

# ── Wrapper that adds an argument ────────────────────
def with_default_timeout(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        kwargs.setdefault("timeout", 30)  # inject default
        return func(*args, **kwargs)
    return wrapper

# ── super() forwarding in class inheritance ───────────
class Animal:
    def __init__(self, name, *args, **kwargs):
        super().__init__(*args, **kwargs)  # cooperative inheritance
        self.name = name

# ── Merging dicts ─────────────────────────────────────
def merge(*dicts):
    result = {}
    for d in dicts:
        result = {**result, **d}      # last wins on conflict
    return result

print(merge({"a":1}, {"b":2}, {"a":99}))
# {"a": 99, "b": 2}

Real-World *args /**kwargs Patterns

These patterns appear constantly in Python frameworks — Django's ORM queries, click CLI args, dataclass builders, print()-like loggers, and more:

Python — real_world_args.py
# ── print()-like logger ───────────────────────────────
from datetime import datetime

def log(*messages, level="INFO", sep=" ", end="\n"):
    """Mimics print() but adds timestamp and level."""
    ts  = datetime.now().strftime("%H:%M:%S")
    msg = sep.join(str(m) for m in messages)
    print(f"[{ts}] {level}: {msg}", end=end)

log("Server started")
log("User", "alice", "logged in", level="DEBUG", sep="|")

# ── ORM-style filter builder ─────────────────────────
class QuerySet:
    def filter(self, **conditions):   # filter(age__gt=18, active=True)
        print(f"WHERE {conditions}")
        return self

    def order_by(self, *fields):       # order_by("name", "-age")
        print(f"ORDER BY {fields}")
        return self

qs = QuerySet()
qs.filter(age__gt=18, active=True).order_by("name", "-score")

# ── Config builder — kwargs with defaults ────────────
def make_config(**overrides):
    defaults = {
        "debug":     False,
        "db_url":    "sqlite:///app.db",
        "log_level": "INFO",
        "timeout":   30,
    }
    return {**defaults, **overrides}   # overrides win

cfg = make_config(debug=True, timeout=60)
print(cfg["log_level"])            # INFO (from defaults)
print(cfg["debug"])               # True (from override)

# ── Type-annotated signatures ─────────────────────────
from typing import Any
def typed_log(*args: Any, level: str = "INFO", **context: Any) -> None:
    print(f"[{level}]", *args, context)

Practice Python Online — Free Compilers

Don't want to install anything yet? Practice all *args and **kwargs examples from this chapter directly in your browser with these free Python environments.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Test every *args and **kwargs example instantly.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • *args in a function definition collects extra positional arguments into a tuple. The name is convention; the * is the syntax. Zero or more extra positional args are allowed.
  • **kwargs collects extra keyword arguments into a dict. The name is convention; the ** is the syntax. Must always be the last parameter.
  • Required parameter order: positional → default → *args → keyword-only → **kwargs. Violating this is a SyntaxError.
  • At call sites, *iterable unpacks a list/tuple into positional arguments; **dict unpacks a dict into keyword arguments.
  • * can also be used in list literals to merge iterables ([*a, *b]) and in assignments to unpack (first, *rest = [...]). ** merges dicts ({**d1, **d2}).
  • / in a signature makes all preceding parameters positional-only (Python 3.8+). * alone makes all following parameters keyword-only.
  • Argument forwarding: def wrapper(*args, **kwargs): func(*args, **kwargs) — essential pattern for decorators and proxy functions.
  • Real-world uses: decorators, print()-like loggers, ORM query builders, config builders with defaults, dict merging, cooperative multi-inheritance with super().
⚡
Free Resource
Download our Python *args & **kwargs Cheat Sheet
*args, **kwargs, parameter order, unpacking, / and * separators, forwarding & real-world patterns — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

*args collects extra positional arguments into a tuple. You can iterate over it, index it, or pass it to any function expecting a tuple.

**kwargs collects extra keyword arguments into a dict. Keys are the argument names (strings), values are the argument values. Use .items(), .get(), etc.

def f(*args, **kwargs):
    print(type(args))   # <class 'tuple'>
    print(type(kwargs)) # <class 'dict'>
✓ Answer

They use the same syntax but do the opposite operation:

  • In a definition — def f(*args): collects (gathers) multiple positional arguments into a single tuple parameter.
  • At a call site — f(*nums): unpacks (spreads) an iterable into individual positional arguments as if you typed them out.

Same duality for **: in definition it collects into a dict; at call site it unpacks a dict into keyword arguments.

✓ Answer

A bare * in a function signature (without a name like *args) is a separator that marks all following parameters as keyword-only:

def f(a, b, *, c, d="default"):
    ...
f(1, 2, c=3)     # ✅  c must be keyword
# f(1, 2, 3)    → TypeError

Use it to force callers to name their arguments — improves readability and prevents accidentally passing arguments in the wrong order.

✓ Answer

Unpack both dicts inside a new dict literal with **:

d1 = {"a": 1, "b": 2}
d2 = {"b": 99, "c": 3}
merged = {**d1, **d2}   # {"a": 1, "b": 99, "c": 3}
# d2's "b" overrides d1's "b" (last wins)

You can also add individual keys: {**defaults, **overrides, "forced_key": value}. This replaces the verbose dict.update() pattern in Python 3.9+.

✓ Answer

A decorator is meant to wrap any function. If the wrapper hardcoded specific parameter names, it would only work for functions with exactly that signature.

*args, **kwargs makes the wrapper transparently collect and forward all arguments — positional and keyword — to the original function, regardless of its signature:

def decorator(func):
    def wrapper(*args, **kwargs):   # works for ANY function
        return func(*args, **kwargs) # forward transparently
    return wrapper
MCQ 1 of 3
What type does *args produce inside the function body?
MCQ 2 of 3
Which is the correct order of parameter types in a function definition?
MCQ 3 of 3
What does first, *rest = [1, 2, 3, 4, 5] assign to rest?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel