*args and **kwargs in Python — Flexible Function Arguments
The Interview Question
What are *args and **kwargs? How and when do you use them?
Expert Answer
*args collects any number of positional arguments into a tuple. **kwargs collects any number of keyword arguments into a dictionary. The names 'args' and 'kwargs' are conventions — the * and ** operators are what matter. They're used when you want a function to accept a variable number of arguments — common in wrapper functions, decorators, and APIs where flexibility matters. The argument order in a function signature must be: regular positional, *args, keyword-only, **kwargs. You can also use * and ** for unpacking: *list_var passes list elements as separate positional arguments, and **dict_var passes dictionary entries as keyword arguments. This unpacking is essential for forwarding arguments in decorators and for merging dictionaries.
Key Points to Hit in Your Answer
- *args → tuple of extra positional arguments
- **kwargs → dict of extra keyword arguments
- Order: def f(a, b, *args, key=val, **kwargs)
- * and ** also work for unpacking: f(*list) and f(**dict)
- Essential in decorators: wrapper(*args, **kwargs) forwards all arguments
- Python 3.5+: {**dict1, **dict2} merges dictionaries
Code Example
# Basic usage
def log(message, *tags, level="INFO", **metadata):
print(f"[{level}] {message}")
print(f" Tags: {tags}") # tuple
print(f" Meta: {metadata}") # dict
log("Server started", "prod", "api", level="DEBUG", host="10.0.0.1")
# [DEBUG] Server started
# Tags: ('prod', 'api')
# Meta: {'host': '10.0.0.1'}
# Unpacking
def point(x, y, z):
return f"({x}, {y}, {z})"
coords = [1, 2, 3]
point(*coords) # point(1, 2, 3) → "(1, 2, 3)"
config = {"x": 10, "y": 20, "z": 30}
point(**config) # point(x=10, y=20, z=30)
# Dictionary merging
defaults = {"theme": "dark", "lang": "en"}
overrides = {"lang": "fr", "debug": True}
merged = {**defaults, **overrides}
# {"theme": "dark", "lang": "fr", "debug": True}
What Interviewers Are Really Looking For
Straightforward question but interviewers listen for precision. Know that *args is a tuple (not a list) and **kwargs is a dict. The argument ordering rule trips people up — positional, *args, keyword-only, **kwargs. Showing unpacking usage (calling f(*list)) demonstrates practical fluency beyond just function definitions.
Practice This Question with AI Grading
Reading about interview questions is a start — but practicing with real-time AI feedback is how you actually get better. Goliath Prep grades your answers instantly and tells you exactly what you're missing.
Start Practicing Free →