Pass a list to a function to act as multiple arguments
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Python, the * operator unpacks a list (or any iterable) into separate positional arguments when calling a function. Similarly, ** unpacks a dictionary into keyword arguments. This technique, called argument unpacking, lets you pass collections of values to functions that expect individual parameters. It is the inverse of *args and **kwargs in function definitions, which collect multiple arguments into a single parameter.
Unpacking a List with *
*numbers expands to 1, 2, 3, so the call becomes add(1, 2, 3).
Unpacking a Dictionary with **
Dictionary keys must match the function parameter names exactly.
Combining * and **
Unpacking Tuples and Other Iterables
* works with any iterable — tuples, sets, generators, and ranges:
Using with *args and **kwargs
Unpacking pairs naturally with *args and **kwargs in function definitions:
Forwarding Arguments
A common pattern for wrapper functions:
Practical Examples
Passing Arguments to print()
Building SQL Queries
Merging Dictionaries
Passing Config to Constructors
Common Pitfalls
- Mismatched argument count: Unpacking a list with the wrong number of elements raises
TypeError.add(*[1, 2])fails ifaddexpects 3 arguments. Ensure the list length matches the function signature. - Dictionary keys not matching parameter names:
**unpacking requires that dictionary keys match the function's parameter names exactly.{'Name': 'Alice'}does not match anameparameter (case-sensitive). - *Unpacking into args captures everything: If a function uses
*args, unpacking a list into it works but you lose individual parameter names. Prefer explicit parameters when the argument count is fixed. - Modifying the list after unpacking: Unpacking evaluates at call time. Changing the list after the function call has no effect on the arguments already passed. This is expected behavior but can confuse developers from languages with pass-by-reference semantics.
- Double unpacking the same key: Passing a keyword both explicitly and via
**raisesTypeError.func(name='Bob', **{'name': 'Alice'})fails becausenameis provided twice.
Summary
- Use
*listto unpack a list into separate positional arguments:func(*[1, 2, 3])becomesfunc(1, 2, 3) - Use
**dictto unpack a dictionary into keyword arguments:func(**{'a': 1})becomesfunc(a=1) *works with any iterable (tuples, ranges, generators, strings)- Combine
*argsand**kwargsin definitions with*and**in calls for flexible argument forwarding - Ensure list length and dictionary keys match the function's expected parameters

