Browse Python Topics ▼
Pick a Web Framework

Variable Arguments with Args and Kwargs

📂 Functions & Modular Code 📘 Lesson 24 of 57

Write flexible, dynamic Python functions that accept variable numbers of positional and keyword arguments using *args and **kwargs.

Consider the built-in print() function in Python. You can call it with one item, two items, or twenty items:

print("Hello")
print("User", 42, "logged in from", "192.168.1.1")

How does print() do that? If you tried writing a normal function with fixed parameters def my_print(a, b):, calling it with three items would immediately crash with TypeError: takes 2 positional arguments but 3 were given.

In computer science, functions that can accept an unpredictable, variable number of arguments are called variadic functions.

Python provides two elegant operators to accomplish this:

  1. *args: Collects extra positional arguments into a tuple.
  2. **kwargs: Collects extra keyword arguments into a dictionary.

1. *args: Gathering Positional Arguments

The single asterisk (*) is the packing operator. When placed before a parameter name, it tells Python:

“Take any extra positional arguments that the caller passed in, bundle them up into a tuple, and assign that tuple to this variable name.”

def sum_all(*numbers):
    print("Received numbers type:", type(numbers))
    print("Raw tuple:", numbers)
    return sum(numbers)

print("Sum:", sum_all(10, 20))
print("Sum:", sum_all(1, 2, 3, 4, 5))
print("Sum:", sum_all())  # Empty call yields an empty tuple ()

Output:

Received numbers type: <class 'tuple'>
Raw tuple: (10, 20)
Sum: 30
Received numbers type: <class 'tuple'>
Raw tuple: (1, 2, 3, 4, 5)
Sum: 15
Received numbers type: <class 'tuple'>
Raw tuple: ()
Sum: 0

[!NOTE] The word args is merely an industry convention (short for “arguments”). You can name the parameter anything valid as long as it starts with an asterisk, such as *scores or *names. However, following *args makes your code immediately familiar to other Python developers.


2. **kwargs: Gathering Keyword Arguments

The double asterisk (**) is the keyword-packing operator. It instructs Python:

“Take any unexpected keyword arguments (key=value), pack them into a dictionary, and hand that dictionary to me.”

def register_user(username, email, **extra_details):
    print(f"Primary: {username} <{email}>")
    print("Extra details dictionary:", extra_details)
    
    # Safely inspect custom fields
    if "theme" in extra_details:
        print(f"Setting UI theme to {extra_details['theme']}")

register_user("alex_dev", "alex@example.com", age=28, country="Canada", theme="dark")

Output:

Primary: alex_dev <alex@example.com>
Extra details dictionary: {'age': 28, 'country': 'Canada', 'theme': 'dark'}
Setting UI theme to dark

3. Strict Parameter Ordering Rules

When combining regular parameters, default values, *args, and **kwargs, Python requires you to arrange them in a strict order:

def func( positional , *args , keyword_only , **kwargs ):
  1. Standard Positional Arguments: Mandatory values.
  2. *args: Variable positional overflow.
  3. Keyword-Only Arguments: Arguments that can only be supplied by name (often with defaults).
  4. **kwargs: Variable keyword overflow.
def generate_report(title, *records, summary=True, **metadata):
    print(f"Report: {title}")
    print(f"Total entries: {len(records)}")
    if summary:
        print("Summary included.")
    for key, val in metadata.items():
        print(f"Meta: {key} = {val}")

generate_report(
    "Quarterly Earnings",
    1200, 1450, 1800,
    summary=True,
    department="Finance",
    quarter="Q3"
)

4. The Call-Site Superpower: Unpacking Arguments

The * and ** operators do not just pack items in definitions—they can also unpack collections when calling a function!

Unpacking a List or Tuple with *

def point_distance(x, y, z):
    return (x**2 + y**2 + z**2) ** 0.5

coords = [3, 4, 12]

# Instead of point_distance(coords[0], coords[1], coords[2]):
distance = point_distance(*coords)
print("3D Distance:", distance)  # 13.0

Unpacking a Dictionary with **

def connect_database(host, port, username, password):
    print(f"Connecting to {username}@{host}:{port}...")

db_config = {
    "host": "db.internal.lan",
    "port": 5432,
    "username": "postgres",
    "password": "secret_password"
}

# Unpack dictionary keys directly into matching parameter names
connect_database(**db_config)

5. Keyword-Only Arguments with Bare *

Sometimes, you want to prevent users from accidentally passing positional arguments that cause confusion.

Consider this function:

def set_permissions(username, is_admin, can_edit):
    pass

# When calling it:
set_permissions("alice", True, False)  # What do True and False mean? "Boolean blindness"!

You can insert a bare * in your parameter list. Everything following the * must be passed as a named keyword argument:

def set_permissions(username, *, is_admin=False, can_edit=False):
    print(f"User: {username} | Admin: {is_admin} | Edit: {can_edit}")

# Calling positionally now raises a TypeError:
# set_permissions("alice", True, False)  # TypeError: takes 1 positional argument but 3 were given

# The caller is forced to be explicit and clear:
set_permissions("alice", is_admin=True, can_edit=True)

Summary & What’s Next

  • *args captures arbitrary positional arguments into an immutable tuple.
  • **kwargs captures arbitrary keyword arguments into a dictionary.
  • Parameter order: Positional $\rightarrow$ *args $\rightarrow$ Keyword-Only $\rightarrow$ **kwargs.
  • Use * and ** at function call sites to unpack lists and dicts.
  • Use a bare * to force callers to name their arguments, preventing bugs.

Next, learn how to create lightweight, one-line functions on the fly with lambdas.

Test your understanding of Variable Arguments with Args and Kwargs

Quick interactive practice questions with instant feedback.

Take Quiz →