How to Use *args and **kwargs in Python Functions
Implement a variadic function that accepts arbitrary positional and keyword arguments using *args and **kwargs.
Python code
20 linesdef display_info(title, *args, **kwargs):
"""Display positional and keyword arguments received."""
print(f"Title: {title}")
print(f"Additional positional args ({len(args)}):")
for i, arg in enumerate(args, 1):
print(f" {i}. {arg}")
print(f"Keyword args ({len(kwargs)}):")
for key, value in kwargs.items():
print(f" {key} = {value}")
if __name__ == "__main__":
display_info(
"User Profile",
"Alice",
"Engineer",
age=30,
city="Berlin",
active=True,
)
Output
Title: User Profile
Additional positional args (2):
1. Alice
2. Engineer
Keyword args (3):
age = 30
city = Berlin
active = True
How it works
The *args parameter collects any number of extra positional arguments into a tuple, while **kwargs gathers extra keyword arguments into a dictionary. Using the * and ** unpacking operators in the function signature allows you to accept a flexible number of inputs. Inside the function, args behaves like a tuple, so you can iterate over it with enumerate() to number each argument. kwargs is a normal dictionary, so you can loop through its items with .items() to access both keys and values. This pattern is especially useful for wrappers, decorators, and APIs that need to forward parameters to other functions.
Common mistakes
- Forgetting that *args is a tuple and **kwargs is a dict, not lists or other types
- Using *args or **kwargs after a required parameter without proper ordering
- Assuming the variable names must be literally 'args' and 'kwargs' — they can be named anything
- Trying to call a function with extra positional arguments when **kwargs is used instead of *args
Variations
- Use `def func(*args, **kwargs)` to accept everything without a required title parameter
- A decorator that passes through arguments using `f(*args, **kwargs)`
Real-world use cases
- Creating a logging wrapper that accepts a message and arbitrary metadata without breaking existing callers.
- Building a configuration loader that merges user-provided overrides with defaults via `**kwargs`.
- Designing a function that forwards optional parameters to multiple downstream calls in an automation script.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.