How to Unpack Function Arguments in Python: Simple Guide
*args for a list or tuple of positional arguments and **kwargs for a dictionary of keyword arguments. Use * to unpack iterables and ** to unpack dictionaries when calling functions.Syntax
To unpack arguments in Python functions, use *args to accept multiple positional arguments as a tuple, and **kwargs to accept multiple keyword arguments as a dictionary.
When calling a function, use * before an iterable to unpack positional arguments, and ** before a dictionary to unpack keyword arguments.
def func(*args, **kwargs): print('Positional args:', args) print('Keyword args:', kwargs) # Calling with unpacking args = (1, 2, 3) kwargs = {'a': 4, 'b': 5} func(*args, **kwargs)
Example
This example shows how to define a function that accepts any number of positional and keyword arguments, and how to call it by unpacking a list and a dictionary.
def greet(*names, **options): greeting = options.get('greeting', 'Hello') for name in names: print(f"{greeting}, {name}!") names_list = ['Alice', 'Bob'] options_dict = {'greeting': 'Hi'} greet(*names_list, **options_dict)
Common Pitfalls
One common mistake is forgetting to use * or ** when unpacking arguments, which causes the function to receive a single iterable or dictionary instead of separate arguments.
Another pitfall is mixing positional and keyword unpacking incorrectly, or using unpacking in the wrong order.
def add(x, y): return x + y nums = (2, 3) # Wrong: passing tuple as single argument # add(nums) # TypeError # Right: unpack tuple into two arguments result = add(*nums) print(result)
Quick Reference
*args: collects extra positional arguments as a tuple.**kwargs: collects extra keyword arguments as a dictionary.- Use
*to unpack lists or tuples when calling functions. - Use
**to unpack dictionaries when calling functions. - Order when defining function parameters: regular, *args, default parameters, **kwargs.