![]() |
VOOZH | about |
Python provides the concept of packing and unpacking arguments, which allows us to handle variable-length arguments efficiently. This feature is useful when we donβt know beforehand how many arguments will be passed to a function.
Packing allows multiple values to be combined into a single parameter using * (for tuples/lists) and ** (for dictionaries).
The * operator allows us to pass multiple arguments to a function and pack them into a tuple.
Packed arguments: (1, 2, 3, 4, 'geeks for geeks')
Explanation:
*args packs all arguments into a tuple.** operator is used to collect multiple keyword arguments into a dictionary.
Packed keyword arguments: {'name': 'Anaya', 'age': 25, 'country': 'India'}
Explanation:
**kwargs collects keyword arguments as a dictionary.kwargs.Unpacking allows values from an iterable (list, tuple, or dictionary) to be passed as separate arguments to a function.
We use * to unpack elements from a list/tuple.
Sum: 16
Explanation: *numbers unpacks numbers into a, b, c.
We use ** to unpack key-value pairs from a dictionary.
Example
Name: geeks for geeks, Age: 30, Country: India
Explanation: **data unpack dictionary values and assign them to parameters.
We can use Packing and Unpacking in same function.
Positional: (1, 2, 3)
Keyword arguments: {'name': 'geeks for geeks', 'age': 30}
Explanation:
*args collects (1, 2, 3) as a tuple.**kwargs collects name="geeks for geeks" and age=30 into a dictionary.Features | Packing | Unpacking |
|---|---|---|
Definition | Collects multiple values into a single variable (tuple, list, or dictionary). | Extracts values from a collection (tuple, list, or dictionary) into individual variables. |
Operator Used |
|
|
Purpose | Allows functions to accept a variable number of arguments. | Allows passing values dynamically to functions or variables. |
Data Structure | Combine multiple values into a single entity (tuple or dictionary). | Extracts multiple values from a single entity into separate variables. |
Example in function definition |
|
|
Example inf unction call |
|
|
Storage Format | Tuple ( | Individual variables or function arguments. |