*args & **kwargs
Flexible Functions
Learn how to write Python functions that accept any number of arguments using the *args and **kwargs syntax.
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.
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.
How the Packing Works
The Syntax Rule
# The correct parameter order is always: def func(regular, *args, **kwargs): ...
*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
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
# Decorator pattern (preview) def log_call(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__}") return func(*args, **kwargs) return wrapper
Common Mistakes
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))