Argument Unpacking
Argument Unpacking is a very handy way of passing variables to functions.Since lists, tuples, dictionaries are used as containers in python. We can pass them to functions too. Lets take an example of a function :
Now, we have a point p1(3,4) represented in python as p1=(3,4). Normally what we do is distance_from_origin(3,4). But with argument unpacking we can use the above function as:
distance_from_origin(*p1). The results for both distance_from_origin(3,4) and distance_from_origin(*p1) will be same where p1=(3,4).
And now let consider another scenario where we represent the point p1 as p1={'x':3,'y':4}. Then we can use the above function as distance_from_origin(**p1). Which will return the result same.
Note: Make sure the number of arguments taken by the function is equal to the number of the elements in the container. i.e. for the function distance_from_origin(x,y) we can't pass p1(2,3,4) as distance_from_origin(*p1).
import math
def distance_from_origin(x,y):
return math.sqrt((x**2)+(y**2))
Now, we have a point p1(3,4) represented in python as p1=(3,4). Normally what we do is distance_from_origin(3,4). But with argument unpacking we can use the above function as:
distance_from_origin(*p1). The results for both distance_from_origin(3,4) and distance_from_origin(*p1) will be same where p1=(3,4).
And now let consider another scenario where we represent the point p1 as p1={'x':3,'y':4}. Then we can use the above function as distance_from_origin(**p1). Which will return the result same.
Note: Make sure the number of arguments taken by the function is equal to the number of the elements in the container. i.e. for the function distance_from_origin(x,y) we can't pass p1(2,3,4) as distance_from_origin(*p1).
Comments
Post a Comment