Python Arguments & Parameters
Understanding how Python passes data into functions is fundamental to writing flexible, reusable code. Python supports six types of function parameters: positional, keyword, default, *args (variable positional), **kwargs (variable keyword), and keyword-only arguments. This chapter covers every type with an anatomy diagram, order rules, common pitfalls (mutable defaults!), and real-world design patterns used in professional Python APIs.
Parameters vs Arguments
These two terms are often used interchangeably, but they have a precise distinction: parameters are the names in the function definition — they are the variables that receive values. Arguments are the actual values passed when the function is called.
SyntaxError
Positional Arguments
Positional arguments are matched to parameters by their order. The
first argument goes to the first parameter, the second to the second, and so on. If you pass the
wrong number, Python raises a TypeError.
def greet(first_name, last_name):
print(f"Hello, {first_name} {last_name}!")
# Positional — order matters!
greet("Alice", "Smith") # Hello, Alice Smith!
greet("Smith", "Alice") # Hello, Smith Alice! ← wrong order
# Too few arguments → TypeError
# greet("Alice") → TypeError: missing 1 positional argument
# Too many → TypeError
# greet("A","B","C") → TypeError: takes 2 positional arguments but 3 were given
# Positional with numeric parameters
def power(base, exponent):
return base ** exponent
print(power(2, 8)) # 256 — base=2, exponent=8
print(power(8, 2)) # 64 — base=8, exponent=2 (order matters!)
Keyword Arguments
Keyword arguments are passed with the parameter name explicitly:
func(name="Alice"). They can be in any order, make the call
self-documenting, and can be mixed with positional arguments (positional must come first).
def create_profile(name, age, city):
print(f"{name}, {age}, from {city}")
# Keyword arguments — ORDER independent
create_profile(name="Alice", age=25, city="Vadodara")
create_profile(city="Vadodara", name="Alice", age=25) # same result
# Mixed: positional first, then keyword
create_profile("Alice", age=25, city="Vadodara") # ✅ OK
# create_profile(name="Alice", 25, "Vadodara") → SyntaxError!
# Why use keyword args?
# Without keywords — hard to read
connect("localhost", 5432, True, "mydb", False)
# With keywords — self-documenting!
connect(
host="localhost",
port=5432,
ssl=True,
database="mydb",
debug=False
)
Default Parameter Values
A parameter can have a default value specified with
= in the function definition. If the caller doesn't supply
that argument, the default is used. Parameters with defaults must come after parameters
without defaults.
def greet(name, greeting="Hello", punctuation="!"):
print(f"{greeting}, {name}{punctuation}")
greet("Alice") # Hello, Alice! ← both defaults used
greet("Bob", "Hi") # Hi, Bob! ← one default
greet("Carol", "Hey", ".") # Hey, Carol. ← no defaults
greet("Dave", punctuation="?") # Hello, Dave? ← keyword override
# ❌ Non-default before default → SyntaxError
# def bad(x=1, y): → SyntaxError
# ════════ MUTABLE DEFAULT TRAP ════════════════════════
# ❌ WRONG — mutable default shared across all calls!
def add_item_bad(item, lst=[]):
lst.append(item)
return lst
print(add_item_bad("a")) # ['a']
print(add_item_bad("b")) # ['a', 'b'] ← BUG! 'a' still there!
# ✅ CORRECT — use None as sentinel
def add_item_good(item, lst=None):
if lst is None:
lst = [] # fresh list every call
lst.append(item)
return lst
print(add_item_good("a")) # ['a']
print(add_item_good("b")) # ['b'] ← correct, independent!
None as the default and create the mutable object
inside the function body.
*args — Variable Positional Arguments
*args allows a function to accept
any number of positional arguments. Inside the function,
args is a tuple containing all extra
positional arguments. The name args is convention — you can
use any name after the *.
# *args collects extra positional args into a tuple
def total(*numbers):
print(type(numbers)) # <class 'tuple'>
return sum(numbers)
print(total(1, 2, 3)) # 6
print(total(1, 2, 3, 4, 5)) # 15
print(total()) # 0 — zero args OK
# Mixing positional param + *args
def log(level, *messages):
for msg in messages:
print(f"[{level}] {msg}")
log("INFO", "Server started")
log("ERROR", "DB down", "retrying...", "failed")
# Unpacking an existing list/tuple into positional args
nums = [10, 20, 30]
print(total(*nums)) # 60 — * unpacks the list
# Forward args to another function
def wrapper(*args):
print("Before call")
result = total(*args) # pass args through
print("After call")
return result
**kwargs — Variable Keyword Arguments
**kwargs allows a function to accept
any number of keyword arguments. Inside the function,
kwargs is a dict containing all extra
keyword arguments. It's widely used in framework code and decorators.
# **kwargs collects extra keyword args into a dict
def profile(**info):
print(type(info)) # <class 'dict'>
for key, val in info.items():
print(f" {key}: {val}")
profile(name="Alice", age=25, city="Vadodara")
# name: Alice age: 25 city: Vadodara
# Mixing params + **kwargs
def create_user(username, email, **extra):
print(f"User: {username}, {email}")
print(f"Extra: {extra}")
create_user("alice", "alice@ex.com", role="admin", active=True)
# Unpacking a dict into keyword args with **
config = {"host": "localhost", "port": 8080}
print("{host}:{port}".format(**config)) # localhost:8080
# Building flexible API functions with *args + **kwargs
def make_request(method, url, *headers, **options):
print(f"{method} {url}")
print(f"Headers: {headers}")
print(f"Options: {options}")
make_request(
"GET", "https://api.example.com/users",
"Content-Type: application/json",
timeout=30, verify_ssl=True
)
Parameter Order Rules & Keyword-Only Arguments
Python enforces a strict order for parameters. Violating it causes a
SyntaxError. Parameters after
*args or after a bare
* are keyword-only — they must be passed by
name, never positionally.
| # | Parameter type | Example | Notes |
|---|---|---|---|
| 1 | Positional (no default) | name |
Required, matched by position |
| 2 | Positional with default | title="Mr" |
Optional; must come after required positional |
| 3 | *args | *extras |
Collects remaining positional → tuple |
| 4 | Keyword-only (no default) | verbose |
Must pass by name; after * or *args |
| 5 | Keyword-only (with default) | debug=False |
Optional keyword-only |
| 6 | **kwargs | **options |
Collects remaining keyword args → dict |
# Full parameter order example
def full_example(pos1, pos2, def1="a", *args, kw_only, kw_def=True, **kwargs):
print(f"pos1={pos1}, pos2={pos2}")
print(f"def1={def1}, args={args}")
print(f"kw_only={kw_only}, kw_def={kw_def}")
print(f"kwargs={kwargs}")
full_example(1, 2, "b", 3, 4, kw_only="required", extra="hi")
# ── Keyword-only with bare * ─────────────────────────
# After *, NO positional args can follow — only keyword-only
def send_email(recipient, *, subject, body, html=False):
print(f"To: {recipient}")
print(f"Subject: {subject} HTML:{html}")
print(f"Body: {body}")
send_email("alice@ex.com", subject="Hello", body="Hi there")
# send_email("a@b.com","Hello","Body") → TypeError!
# subject and body MUST be keyword args
# ── Positional-only (Python 3.8+) ────────────────────
# Parameters before / can ONLY be passed positionally
def divide(dividend, divisor, /):
return dividend / divisor
print(divide(10, 2)) # 5.0 ✅
# divide(dividend=10, divisor=2) → TypeError!
# ── All types together ───────────────────────────────
def everything(pos_only, /, normal, *, kw_only, **kwargs):
print(pos_only, normal, kw_only, kwargs)
everything(1, 2, kw_only=3)
everything(1, normal=2, kw_only=3, extra="ok")
def wrapper(*args, **kwargs) accepts
any combination of arguments. Call another function with
func(*args, **kwargs) to forward everything unchanged — the
standard pattern for decorators, middleware, and proxy functions.
Practice Python Online — Free Compilers
Don't want to install anything yet? Practice all argument and parameter examples from this chapter directly in your browser with these free Python environments.
- Parameters are names in the function definition; arguments are values passed at the call site.
- Positional arguments are matched by order. Keyword arguments are matched by name and can appear in any order.
-
Default values make parameters optional. Non-default params must come
before default params. Never use mutable objects as defaults — use
Noneas sentinel. -
*argscollects any number of extra positional arguments into a tuple. -
**kwargscollects any number of extra keyword arguments into a dict. -
Keyword-only parameters appear after
*argsor a bare*— they must be passed by name. -
Positional-only parameters (Python 3.8+) appear before
/— they cannot be passed by keyword. -
Required parameter order:
positional → default → *args → keyword-only → **kwargs. -
def fn(*args, **kwargs)is the universal forwarder — used in decorators and proxy functions to pass all arguments unchanged.
A parameter is the variable name defined in the function signature — it exists in the function definition. An argument is the actual value passed when the function is called.
def greet(name): # name is a PARAMETER
print(name)
greet("Alice") # "Alice" is an ARGUMENT
Default values are evaluated once at function definition time, not at each call. If the default is a mutable object (list, dict, set), all calls share the same object — mutations from one call persist to the next.
# ❌ WRONG
def bad(lst=[]):
lst.append(1)
return lst
print(bad()) # [1]
print(bad()) # [1, 1] ← BUG!
# ✅ CORRECT — use None sentinel
def good(lst=None):
if lst is None: lst = []
lst.append(1)
return lst
*args collects all extra positional
arguments into a tuple. It is always a tuple, even when no
extra arguments are passed (empty tuple ()).
**kwargs collects all extra keyword
arguments into a dict. It is always a dict, even when no extra
keyword arguments are passed (empty dict
{}).
def demo(*args, **kwargs):
print(type(args)) # <class 'tuple'>
print(type(kwargs)) # <class 'dict'>
Keyword-only arguments are parameters that must be
passed by name — they cannot be supplied positionally. You define them by
placing them after *args or after a bare
* (when you don't want any variable
positional args).
def send(to, *, subject, body): # bare * enforces keyword-only
pass
send("a@b.com", subject="Hi", body="Hello") # ✅
# send("a@b.com","Hi","Hello") → TypeError
Python enforces this strict order (left to right):
-
Positional-only (before
/, Python 3.8+) - Regular positional (no default)
- Positional with default
- *args (variable positional)
- Keyword-only (no default)
- Keyword-only with default
- **kwargs (variable keyword)
Deviating from this order causes a
SyntaxError.
*args?
Rate Us on Google
Join Our Learning Community
Connect with thousands of learners, get daily tips, ask questions and stay updated with new tutorials.