1. What Is Argument Unpacking?
Argument unpacking refers to using a specific syntax during a function call to expand the data in an iterable object or mapping object and pass it as individual function arguments.
Python mainly uses two forms of unpacking:
*: expands an iterable object into positional arguments.**: expands a mapping object into keyword arguments.
For example:
def add(a, b, c):
return a + b + c
numbers = [10, 20, 30]
print(add(*numbers))
Output:
60
Here, *numbers expands the three elements in the list, which is equivalent to:
add(10, 20, 30)
Now let's look at a dictionary unpacking example:
def introduce(name, age, city):
print(name, age, city)
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
introduce(**user)
Output:
Alice 25 Tokyo
It is equivalent to:
introduce(
name="Alice",
age=25,
city="Tokyo"
)
The core value of argument unpacking is this: it converts the contents of a data structure into the positional arguments or keyword arguments required by a function call.
2. Using * to Unpack Positional Arguments
A single asterisk * can expand a list, tuple, or other iterable object into multiple positional arguments.
1. Unpacking a List
def calculate(a, b, c):
return a + b + c
numbers = [10, 20, 30]
result = calculate(*numbers)
print(result)
Output:
60
Equivalent to:
calculate(10, 20, 30)
Each element in the list is matched, in iteration order, to the function's parameters in turn.
2. Unpacking a Tuple
def introduce(name, age, city):
print(f"姓名:{name}")
print(f"年龄:{age}")
print(f"城市:{city}")
user = ("Alice", 25, "Tokyo")
introduce(*user)
Output:
姓名:Alice
年龄:25
城市:Tokyo
Like lists, tuples can also be unpacked with a single asterisk.
3. Unpacking a String
A string is also an iterable object, so it can be unpacked with * as well.
def show(a, b, c):
print(a, b, c)
show(*"ABC")
Output:
A B C
The string is iterated character by character, and each character becomes a positional argument.
In real-world development, however, this is generally not recommended unless you genuinely need to pass arguments character by character, because it easily makes the intent of the code unclear.
4. Unpacking a range Object
def add(a, b, c, d):
return a + b + c + d
numbers = range(1, 5)
print(add(*numbers))
Output:
10
The elements produced by range(1, 5) are expanded in order into four positional arguments.
5. The Unpacked Object Must Satisfy the Argument Count Requirement
def add(a, b, c):
return a + b + c
numbers = [10, 20]
add(*numbers)
A TypeError is raised at runtime, because the function requires three positional arguments while the unpacking provides only two.
If the number of arguments exceeds what the function can accept, an argument-binding error is likewise raised.
numbers = [10, 20, 30, 40]
add(*numbers)
Therefore, when using * unpacking, you need to ensure that the number of arguments after expansion matches the function signature.
3. Using ** to Unpack Keyword Arguments
The double asterisk ** is used to expand a mapping object such as a dictionary into keyword arguments.
1. Unpacking a Dictionary
def create_user(name, age, city):
print(name, age, city)
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
create_user(**user)
Output:
Alice 25 Tokyo
Here:
namecorresponds to the function parametername.agecorresponds to the function parameterage.citycorresponds to the function parametercity.
The dictionary keys determine the keyword argument names, and the dictionary values serve as the arguments for the corresponding parameters.
2. Dictionary keys must meet keyword argument requirements
def show(name, age):
print(name, age)
user = {
"name": "Alice",
"age": 25
}
show(**user)
This runs normally.
If the dictionary contains keys that do not meet the function parameter name requirements and there is no corresponding **kwargs to receive them, a TypeError may occur.
def show(name, age):
print(name, age)
user = {
"name": "Alice",
"age": 25,
"city": "Tokyo"
}
show(**user)
The reason for the error is that the function does not define a city parameter, and there is no variable keyword parameter to receive it.
In addition, when using ** unpacking, the keys in the mapping must be strings and must meet the requirements for keyword argument passing.
3. Dictionary unpacking and default parameters
If function parameters have default values, the dictionary can provide only some of the parameters.
def connect(host, port=8080, timeout=10):
print(host, port, timeout)
config = {
"host": "localhost",
"timeout": 30
}
connect(**config)
Output:
localhost 8080 30
Here:
hostis obtained from the dictionary.portis not provided, so the default value8080is used.timeoutis obtained from the dictionary.
4. Dictionary unpacking supports multiple mapping objects
In a function call, multiple ** can be used consecutively.
def create_user(name, age, city):
print(name, age, city)
basic = {
"name": "Alice",
"age": 25
}
location = {
"city": "Tokyo"
}
create_user(**basic, **location)
Output:
Alice 25 Tokyo
Parameters from multiple mapping objects participate together in function parameter binding.
If multiple dictionaries provide the same keyword name, a duplicate binding error occurs.
basic = {
"name": "Alice"
}
other = {
"name": "Bob"
}
create_user(**basic, **other)
This produces a TypeError because name is passed more than once.
If you want to merge dictionaries and have later values override earlier values, you can merge the dictionaries first and then unpack them:
basic = {
"name": "Alice",
"age": 25
}
other = {
"name": "Bob",
"city": "Tokyo"
}
config = {**basic, **other}
create_user(**config)
Output:
Bob 25 Tokyo
Here, the dictionary merge happens before the function call, and the later name overrides the earlier name.
IV. Using * and ** unpacking together
Python allows positional argument unpacking and keyword argument unpacking to be used together in the same function call.
1. Basic combination
def create_order(product, quantity, price, currency="CNY"):
print(product, quantity, price, currency)
args = ("Laptop", 2)
kwargs = {
"price": 5999,
"currency": "CNY"
}
create_order(*args, **kwargs)
Output:
Laptop 2 5999 CNY
Where:
*argsis expanded into positional arguments.**kwargsis expanded into keyword arguments.
This is equivalent to:
create_order(
"Laptop",
2,
price=5999,
currency="CNY"
)
2. Mixing ordinary arguments with unpacked arguments
def introduce(name, age, city, job):
print(name, age, city, job)
basic = ["Alice", 25]
extra = {
"city": "Tokyo",
"job": "Engineer"
}
introduce(*basic, **extra)
Output:
Alice 25 Tokyo Engineer
A function call can combine fixed arguments, positional unpacking, and keyword unpacking.
3. Positional and keyword arguments cannot bind the same parameter twice
def introduce(name, age):
print(name, age)
data = {
"name": "Bob",
"age": 25
}
introduce("Alice", **data)
This raises a TypeError.
The reason is:
"Alice"is already bound tonameas a positional argument.**dataalso suppliesname="Bob".- The same parameter is assigned twice.
The correct way to write it:
introduce("Alice", age=25)
4. The complete process of argument unpacking
flowchart TD
A["Prepare the data for the function call"] --> B{"Is unpacking needed?"}
B -->|No| C["Pass the arguments directly"]
B -->|Yes| D{"Unpacking method"}
D -->|Single asterisk| E["Expand the iterable"]
D -->|Double asterisk| F["Expand the mapping object"]
E --> G["Produce positional arguments"]
F --> H["Produce keyword arguments"]
C --> I["Perform argument binding"]
G --> I
H --> I
I --> J{"Did binding succeed?"}
J -->|Yes| K["Execute the function body"]
J -->|No| L["Raise TypeError"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#FFF5DE,stroke:#E8D29A,color:#334155
style C fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style F fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style H fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style J fill:#FFF5DE,stroke:#E8D29A,color:#334155
style K fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style L fill:#FBE9E9,stroke:#D9AAAA,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
V. Parameter Collection in Function Definitions vs. Argument Unpacking in Function Calls
This is one of the most easily confused topics in Python's function argument mechanism.
*args and **kwargs can appear both in function definitions and in function calls, but they serve different purposes.
1. Parameter Collection in Function Definitions
def show(*args, **kwargs):
print(args)
print(kwargs)
show(10, 20, name="Alice", age=25)
Output:
(10, 20)
{'name': 'Alice', 'age': 25}
Here:
*argsin a function definition collects extra positional arguments.**kwargsin a function definition collects extra keyword arguments.
2. Argument Unpacking in Function Calls
def show(a, b, name, age):
print(a, b, name, age)
args = (10, 20)
kwargs = {
"name": "Alice",
"age": 25
}
show(*args, **kwargs)
Here:
*argsin a call expression expands a tuple.**kwargsin a call expression expands a dictionary.
3. Collection vs. Unpacking
| Where Used | Syntax | Purpose | Result |
|---|---|---|---|
| Function definition | *args |
Collects positional arguments | Tuple |
| Function definition | **kwargs |
Collects keyword arguments | Dictionary |
| Function call | *values |
Expands an iterable | Positional arguments |
| Function call | **config |
Expands a mapping object | Keyword arguments |
A simple way to remember:
When defining a function, the asterisk collects; when calling a function, the asterisk expands.
VI. Multi-Level Unpacking and Nested Structures in Python
Beyond simple lists, tuples, and dictionaries, Python also supports argument unpacking with complex, combined data structures.
1. Unpacking Nested Lists
def create_point(x, y, z):
print(f"坐标:{x}, {y}, {z}")
point = [10, [20, 30]]
create_point(point[0], *point[1])
Output:
坐标:10, 20, 30
Here, the first element of the outer list is passed as an ordinary positional argument, and then the inner list is expanded.
2. Merging Multiple Configurations with Dictionaries
def connect(host, port, timeout, retry):
print(host, port, timeout, retry)
default_config = {
"host": "localhost",
"port": 8080,
"timeout": 10,
"retry": 3
}
custom_config = {
"timeout": 30,
"retry": 5
}
config = {
**default_config,
**custom_config
}
connect(**config)
Output:
localhost 8080 30 5
This approach is commonly used for:
- Merging default configuration with user configuration.
- Environment configuration overrides.
- Combining API request parameters.
- Multi-level configuration management.
Note that {**a, **b} creates a new dictionary; it does not recursively merge nested dictionaries inside.
For example:
default = {
"database": {
"host": "localhost",
"port": 3306
}
}
custom = {
"database": {
"host": "db.example.com"
}
}
config = {
**default,
**custom
}
print(config)
Result:
{
'database': {
'host': 'db.example.com'
}
}
The entire database value is replaced, rather than only the host within it being overwritten.
3. Building a New Dictionary with Dictionary Unpacking
user = {
"name": "Alice",
"age": 25
}
extra = {
"city": "Tokyo",
"job": "Engineer"
}
profile = {
**user,
**extra,
"active": True
}
print(profile)
Output:
{
'name': 'Alice',
'age': 25,
'city': 'Tokyo',
'job': 'Engineer',
'active': True
}
This pattern is very common in data transformation, configuration composition, and constructing request parameters.
7. The Difference Between Unpacking and Iterable Unpacking
Python also has another syntax that is easily confused with function argument unpacking: sequence unpacking.
For example:
a, b, c = [10, 20, 30]
print(a, b, c)
This is also unpacking, but it is not argument unpacking in a function call.
1. Sequence Unpacking
Sequence unpacking is used to assign elements from an iterable to multiple variables.
numbers = [10, 20, 30]
a, b, c = numbers
2. Extended Sequence Unpacking
Using a single asterisk can collect the remaining elements.
numbers = [10, 20, 30, 40, 50]
first, *middle, last = numbers
print(first)
print(middle)
print(last)
Output:
10
[20, 30, 40]
50
Here, *middle collects the remaining elements, and the result is a list.
3. Comparison of Three Unpacking Forms
| Unpacking Form | Main Use | Result |
|---|---|---|
Function call * |
Expand positional arguments | Multiple positional parameters |
Function call ** |
Expand keyword arguments | Multiple keyword parameters |
Assignment statement * |
Collect remaining elements | List |
For example: