Args and Kwargs
The * and ** operators are used both in function definitions and in function calls, with different meanings. In a function call, *iterable unpacks an itera...
Unpacking with * in Calls
The * and ** operators are used both in function definitions and in function calls, with different meanings. In a function call, *iterable unpacks an iterable into positional arguments. Example: def add(a, b, c): return a+b+c; nums = [1, 2, 3]; add(*nums) is equivalent to add(1, 2, 3). This is useful when you have data in a list and want to pass each element as a separate argument without manually indexing them.
Unpacking with ** in Calls
In a function call, **dictionary unpacks key-value pairs into keyword arguments. Example: def greet(name, greeting): print(f"{greeting}, {name}"); params = {"name": "Alice", "greeting": "Hi"}; greet(**params) is equivalent to greet(name="Alice", greeting="Hi"). The keys in the dictionary must match the parameter names exactly. This is a powerful pattern for passing configuration dictionaries to functions or forwarding keyword arguments between wrapper functions.
Combining *args and **kwargs
A function can accept both *args and **kwargs together: def versatile(*args, **kwargs): print(args, kwargs). Calling versatile(1, 2, key="val") prints (1, 2) {'key': 'val'}. This pattern is used extensively in decorator functions that need to work with any wrapped function, regardless of its signature. The combination allows the decorator to forward all arguments unchanged using: return wrapped_function(*args, **kwargs).
Forwarding Arguments in Decorators
The most common real-world use of *args and **kwargs is in decorators. def log_call(func): def wrapper(*args, **kwargs): print(f"Calling {func.__name__}"); result = func(*args, **kwargs); return result; return wrapper. The wrapper captures all arguments with *args, **kwargs and passes them unchanged to the original function. Without this, the decorator would only work with functions of a specific signature, making it useless as a general-purpose tool.
Extended Iterable Unpacking
Python 3 supports extended unpacking in assignment expressions using the * operator. first, *rest = [1, 2, 3, 4, 5]. After this, first is 1 and rest is [2, 3, 4, 5]. Similarly, *init, last = [1, 2, 3, 4, 5] gives init as [1, 2, 3, 4] and last as 5. This is far more readable than using slicing. You can also use it in the middle: a, *middle, b = [1, 2, 3, 4, 5] gives a=1, middle=[2,3,4], b=5.
Exam Tip
Exam questions about *args and **kwargs test two things: their type inside the function (args is a tuple, kwargs is a dict) and their position in a function signature (positional params, then *args, then keyword-only, then **kwargs). A common question: def f(*args, **kwargs): print(type(args)); — what is printed? <class 'tuple'>. Another: can you have **kwargs before *args? No — that is a SyntaxError. The star forms must follow the fixed positional parameters.