9. *args & **kwargs & Unpacking
Master flexible function parameters: `def example(*args)` for variable positional arguments (tuples), `def example(**kwargs)` for variable keyword arguments (dictionaries), list unpacking (`print(*numbers)`), and dictionary unpacking (`function(**data)`).
🎓 Junior Python Curriculum — Select Module
9. Python *args & **kwargs (Packing, Unpacking & Signature Rules)
1️⃣ Positional Argument Packing: `def example(*args)`
The *args syntax allows a function to accept any number of positional arguments. Inside the function body, args is bound to an immutable tuple.
for arg in args:
print(arg)
example(1, 2, 3) # args becomes (1, 2, 3)
2️⃣ Keyword Argument Packing: `def example(**kwargs)`
The **kwargs syntax allows a function to accept arbitrary keyword arguments (key=value). Inside the function body, kwargs is bound to a standard dict.
for key, value in kwargs.items():
print(f"{key} = {value}")
example(name="Dilshad", age=30) # kwargs becomes {"name": "Dilshad", "age": 30}
3️⃣ Iterable Unpacking: `print(*numbers)`
When calling a function, prefixing a list, tuple, or generator with * unpacks its individual elements as distinct positional arguments.
print(*numbers) # Equivalent to print(1, 2, 3) -> Output: 1 2 3
# Also useful for merging lists:
combined = [*numbers, 4, 5] # [1, 2, 3, 4, 5]
4️⃣ Dictionary Unpacking: `function(**data)`
Prefixing a dictionary with ** unpacks its key-value pairs as keyword arguments matching function parameter names.
print(f"Hello {name}, you are {age} years old.")
data = {"name": "Dilshad", "age": 30}
greet_developer(**data) # Equivalent to greet_developer(name="Dilshad", age=30)
# Also useful for merging dictionaries:
merged_dict = {**data, "role": "Engineer"}
5️⃣ Mandatory Parameter Ordering Rules
When combining multiple parameter types in Python function signatures, you must strictly follow this order:
""" 1. Positional-only parameters (before /) 2. Standard positional/keyword parameters 3. *args variadic positional collector 4. Keyword-only parameters (after * or *args) 5. **kwargs variadic keyword collector """