Packing and Unpacking in Python (Arguments)
Packing and Unpacking in Python :
Packing: As it packs all the arguments into a single variable, that this method call receives into a tuple called args ( We can use any variable name in place of args).
- Example: def func( *args )
Unpacking: Unpacking in Python refers to an operation where values of list or tuple are assigned to a single variable in a single assignment statement.
- Example : ( a , b ,c ) =Tuple/list
Let’s understand Packing and Unpacking.
When to use :
- Consider a situation where we have a function that receives six arguments. We want to make a call to this function and we have a list of size Six with us that has all arguments for the function. If we simply pass a list to the function, the call doesn’t work.
- We have to call a function and want to pass arguments and we don’t have any idea of the number of arguments the function can receive.
Let’s Understand Packing and Unpacking in Python with some examples –
code #1 :
The sum of the list is: 1001
Note: In the above program we must know the length of the list to define the sum1 function.
Code #3 :
The sum of the values of dictionary is: 16
Note: ** is used for the dictionary.
Code #4 :
The sum of the values of is: 15
The sum of the values of is: 30