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 :
#unpacking
#rishikesh
# Program to understand about
# packing and unpacking in Python
# this lines PACKS values
# into variable a as list type
a = [‘Hi’, 999, ‘Prepsters’]
# this lines UNPACKS values
# of variable a
(wel_w, num, org) = a
print(wel_w)
print(num)
print(org)
Output :
Hi
999
Prepsters
Code #2:
#unpacking
#rishikesh
# Program to understand about
# packing and unpacking in Python
def sum1(a,b,c):
return (a+b+c)
a = [1, 999, 1]
print(‘The sum of the list is: ‘,sum1(*a))
Output :
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 :
#unpacking
#rishikesh
# Program to understand about
# packing and unpacking in Python
def fun(a, b, c):
return (a+b+c)
# A call with unpacking of dictionary
d = {‘a’:2, ‘b’:4, ‘c’:10}
x=fun(**d)
print(‘The sum of the values of dictionary is: ‘,x)
Output :
The sum of the values of dictionary is: 16
Note: ** is used for the dictionary.
Code #4 :
#packing
#rishikesh
# Program to understand about
# packing and unpacking in Python
# This function uses packing to sum
# unknown number of arguments
def mySum(*args):
return sum(args)
print(‘The sum of the values of is: ‘ , mySum(1, 2, 3, 4, 5))
print(‘The sum of the values of is: ‘ , mySum(10, 20))
Output :
The sum of the values of is: 15
The sum of the values of is: 30
Login/Signup to comment