01 / 20
* args ** kwargs

*args & **kwargs
Flexible Functions

Learn how to write Python functions that accept any number of arguments using the *args and **kwargs syntax.

Python

The Flexibility Problem

Imagine you want to write a function that adds numbers together. How many parameters should it have? Two? Three? Ten?

# This only works for exactly 2 numbers
def add(a, b):
    return a + b

print(add(1, 2))      # 3  ✓
print(add(1, 2, 3))   # TypeError  ✕

What is *args?

The *args syntax lets a function accept any number of positional arguments. The asterisk * tells Python to pack all extra positional arguments into a tuple.

* (single star)
Packs positional arguments into a tuple
args
Just a convention: you can name it anything (e.g., *numbers)
Result
Inside the function, args is an ordinary tuple you can iterate over

What is **kwargs?

The **kwargs syntax lets a function accept any number of keyword arguments. The double asterisk ** tells Python to pack them into a dictionary.

** (double star)
Packs keyword arguments into a dict
kwargs
Convention: short for "keyword arguments", but any name works
Result
Inside the function, kwargs is a standard dict with string keys

How the Packing Works

greet("Hi", "Bye", name="Alice", age=16) def greet(*args, **kwargs): *args (tuple) ("Hi", "Bye") Positional arguments packed in order into a tuple **kwargs (dict) {"name":"Alice","age":16} Keyword arguments packed into a dictionary

The Syntax Rule

# The correct parameter order is always:
def func(regular, *args, **kwargs):
    ...
1
Regular parameters come first: fixed, named arguments.
2
*args comes next: catches all remaining positional arguments.
3
**kwargs comes last: catches all remaining keyword arguments.

*args vs **kwargs

*args **kwargs
Syntax *args **kwargs
Collects Positional arguments Keyword arguments
Data type tuple dict
Access by Index: args[0] Key: kwargs["name"]
Iteration for x in args for k, v in kwargs.items()
Order in def Before **kwargs Always last

How to Use Them

1
Identify whether your function needs a flexible number of positional values, keyword values, or both.
2
Add *args to the parameter list if you need unlimited positional arguments.
3
Add **kwargs if you need unlimited keyword arguments. Always place it after *args.
4
Use the data inside the function: loop over the tuple (*args) or iterate the dict (**kwargs).
5
Call the function with as many arguments as you need. Python handles the packing automatically.

Example 1: *args Sum

def add_all(*numbers):
    # numbers is a tuple, e.g., (1, 2, 3, 4)
    total = 0
    for n in numbers:
        total += n
    return total

print(add_all(1, 2))           # 3
print(add_all(1, 2, 3, 4))     # 10
print(add_all(10))              # 10
print(add_all())                # 0

Example 2: **kwargs Profile

def build_profile(**info):
    # info is a dict, e.g., {"name":"Alice","age":16}
    for key, value in info.items():
        print(f"{key}: {value}")

build_profile(name="Alice", age=16, grade="11th")
# Output:
# name: Alice
# age: 16
# grade: 11th

Example 3: Combining Both

def log_event(event, *tags, **details):
    print(f"Event: {event}")
    print(f"Tags:  {tags}")
    print(f"Info:  {details}")

log_event("login", "web", "mobile",
          user="Alice", status="success")

# Event: login
# Tags:  ('web', 'mobile')
# Info:  {'user': 'Alice', 'status': 'success'}

Unpacking with * and **

You can also use * and ** when calling a function to unpack a list or dict into separate arguments.

def greet(first, last, age):
    print(f"{first} {last}, age {age}")

# Unpacking a list with *
data = ["Alice", "Smith", 16]
greet(*data)  # Alice Smith, age 16

# Unpacking a dict with **
info = {"first": "Bob", "last": "Lee", "age": 17}
greet(**info)  # Bob Lee, age 17

Real-World Use Cases

Wrapper Functions
Pass all arguments through to another function without listing each one.
Decorators
Decorators use *args and **kwargs to wrap any function signature.
Flexible APIs
Libraries accept optional config via **kwargs for backward compatibility.
# Decorator pattern (preview)
def log_call(func):
    def wrapper(*args, **kwargs):
        print(f"Calling {func.__name__}")
        return func(*args, **kwargs)
    return wrapper

Common Mistakes

✕ Wrong Order
Placing **kwargs before *args in the function definition causes a SyntaxError.
✕ Treating args as a List
*args produces a tuple, not a list. You cannot use .append() or .sort() on it directly.
✕ Forgetting the Stars
Writing args without * makes it a normal parameter. The star is what triggers packing.

Summary Cheatsheet

Concept Syntax Produces
Collect positional *args in def tuple
Collect keyword **kwargs in def dict
Unpack list/tuple *my_list in call separate positional args
Unpack dict **my_dict in call separate keyword args
Correct order regular, *args, **kwargs no SyntaxError

Question 1 of 5

What data type does *args collect its values into inside a function?

Question 2 of 5

Which function signature is syntactically valid?

Question 3 of 5

Given the code below, what does print(info) output?

def show(**info):
    print(info)

show(x=1, y=2)

Question 4 of 5

What does the * do when used in a function call like func(*my_list)?

Question 5 of 5

Given the code below, what is printed?

def total(start, *nums):
    s = start
    for n in nums:
        s += n
    return s

print(total(100, 5, 10, 15))