In this article we will discuss how to unpack a list, tuple and dictionary to function arguments.
Suppose we have a function with 3 parameters i.e.
def updateStudentDetail(name, phone, address): print("**********************") print("Student Name : ", name) print("Student phone : ", phone) print("Student address : ", address)
We can call this function and pass three arguments like this,
updateStudentDetail("Riti", "3343" , "Delhi")
But many times we want to pass arguments which are in some other objects like in list or tuple or dictionary to function. We can automatically unpacking the elements in these objects instead of accessing them individually and passing them to function. Let’s see how to do that,
Unpack elements in list or tuple to function arguments using *
Python provides a symbol * , on prefixing this with list will automatically unpack the list elements to function arguments. For example,
Suppose we have a list of ints i.e.
Frequently Asked:
details = ["Riti", "3343" , "Delhi"]
Let’s unpack this list elements to function arguments by symbol * i.e.
# Auto unpack elements in list to function arguments with * updateStudentDetail(*details)
Output of the function will be,
Student Name : Riti Student phone : 3343 Student address : 3343
On similar line we can use tuple with * to unpack its elements to function arguments too i.e.
# A tuple details = ("Riti", "3343" , "Delhi")
Output of the function will be,
Student Name : Riti Student phone : 3343 Student address : Delhi
But we need to make sure that elements in list or tuple are exactly equal to function parameters. Otherwise it will cause error. Therefore its generally used with functions that accepts variable length arguments i.e.
def calculateAverage(*args): ''' Function that accept variable length arguments ''' num = len(args) if num == 0: return 0; sumOfNumbers = 0 for elem in args: sumOfNumbers += elem return sumOfNumbers / num
This function can accept n number of arguments. Now lets pass different size lists to this function and automatically unpack them i.e
list1 = [1,2,3,4,5,6,7,8] list2 = [1,2,3,4,5] list3 = [1,2,3] avg = calculateAverage( *list1) print("Average = " , avg) avg = calculateAverage(*list2) print("Average = " , avg) avg = calculateAverage(*list3) print("Average = " , avg)
Output:
Average = 4.5 Average = 3.0 Average = 2.0
Unpack elements in dictionary to function arguments using **
Python provides an another symbol ** . On prefixing it with a dictionary, all the key value pairs in dictionary will be unpacked to function arguments. Let’s understand this by an example,
As we have a function that accepts 3 parameters i.e.
def updateStudentDetail(name, phone, address): print("**********************") print("Student Name : ", name) print("Student phone : ", phone) print("Student address : ", address)
and a dictionary whose key are with same name as function parameters i.e.
details = { 'name' : 'Sam' , 'phone' : '112' , 'address' : 'London' }
As keys in dictionary are of same name as function arguments, so applying symbol ** on this dictionary will unpack all the values to function arguments i.e.
# Auto unpack dictionary to function arguments with ** updateStudentDetail(**details)
Output:
Student Name : Sam Student phone : 112 Student address : London
But we need to make sure that key names are same as function parameter names, also their count should be same too. Otherwise unpacking will cause Error. Therefore, its generally use with function that accepts variable length key value pairs in arguments i.e.
def updateDetails(**kwargs): ''' Function that accept variable length key value pairs ''' print("**********************") if 'name' in kwargs : print("Student Name : ", kwargs['name']) if 'phone' in kwargs : print("Student phone : ", kwargs['phone']) if 'address' in kwargs : print("Student address : ", kwargs['address'])
This can accept variable length key value pair as arguments. Let’s pass different size dictionaries to this function with auto unpacking using **,
details = { 'name' : 'Sam' , 'phone' : '112' } # Auto unpack dictionary to function arguments with ** updateDetails(**details)
Output :
Student Name : Sam Student phone : 112
Another example,
details = { 'name' : 'Sam' , 'section' : 'A' , 'address' : 'London' , 'phone' : '112' } # Auto unpack dictionary to function arguments with ** updateDetails(**details)
Output:
Student Name : Sam Student phone : 112 Student address : London
Complete example is as follows,
def updateStudentDetail(name, phone, address): print("**********************") print("Student Name : ", name) print("Student phone : ", phone) print("Student address : ", address) def calculateAverage(*args): ''' Function that accept variable length arguments ''' num = len(args) if num == 0: return 0; sumOfNumbers = 0 for elem in args: sumOfNumbers += elem return sumOfNumbers / num def updateDetails(**kwargs): ''' Function that accept variable length key value pairs ''' print("**********************") if 'name' in kwargs : print("Student Name : ", kwargs['name']) if 'phone' in kwargs : print("Student phone : ", kwargs['phone']) if 'address' in kwargs : print("Student address : ", kwargs['address']) if __name__ == '__main__': updateStudentDetail("Riti", "3343" , "Delhi") print("****** Unpack a List to Function Arguments ******") details = ["Riti", "3343" , "Delhi"] updateStudentDetail(details[0], details[1] , details[1]) # Auto unpack elements in list to function arguments with * updateStudentDetail(*details) print("****** Unpack a tuple to Function Arguments ******") details = ("Riti", "3343" , "Delhi") # Auto unpack elements in tuple to function arguments with * updateStudentDetail(*details) print("****** Unpack Lists of different size to Function Arguments ******") list1 = [1,2,3,4,5,6,7,8] list2 = [1,2,3,4,5] list3 = [1,2,3] avg = calculateAverage( *list1) print("Average = " , avg) avg = calculateAverage(*list2) print("Average = " , avg) avg = calculateAverage(*list3) print("Average = " , avg) print("****** Unpack a dictionary to Function Arguments ******") details = { 'name' : 'Sam' , 'phone' : '112' , 'address' : 'London' } # Auto unpack dictionary to function arguments with ** updateStudentDetail(**details) print("****** Unpack a different size dictionaries to Function Arguments ******") details = { 'name' : 'Sam' , 'phone' : '112' } # Auto unpack dictionary to function arguments with ** updateDetails(**details) details = { 'name' : 'Sam' , 'section' : 'A' , 'address' : 'London' , 'phone' : '112' } # Auto unpack dictionary to function arguments with ** updateDetails(**details)
Output:
********************** Student Name : Riti Student phone : 3343 Student address : Delhi ****** Unpack a List to Function Arguments ****** ********************** Student Name : Riti Student phone : 3343 Student address : 3343 ********************** Student Name : Riti Student phone : 3343 Student address : Delhi ****** Unpack a tuple to Function Arguments ****** ********************** Student Name : Riti Student phone : 3343 Student address : Delhi ****** Unpack Lists of different size to Function Arguments ****** Average = 4.5 Average = 3.0 Average = 2.0 ****** Unpack a dictionary to Function Arguments ****** ********************** Student Name : Sam Student phone : 112 Student address : London ****** Unpack a different size dictionaries to Function Arguments ****** ********************** Student Name : Sam Student phone : 112 ********************** Student Name : Sam Student phone : 112 Student address : London
This is, without a doubt, the BEST and most comprehensive explanation of this process that I have ever read. Thank you so much! You helped me solve this exact problem I was having with formatting from a concise set of dictionary data.