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.

We can call this function and pass three arguments like this,

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.

Let’s unpack this list elements to function arguments by symbol * i.e.

Output of the function will be,

On similar line we can use tuple with * to unpack its elements to function arguments too i.e.

Output of the function will be,

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.

This function can accept n number of arguments. Now lets pass different size lists to this function and automatically unpack them i.e

Output:

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.

and a dictionary whose key are with same name as function parameters i.e.

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.

Output:

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.

This can accept variable length key value pair as arguments. Let’s pass different size dictionaries to this function with auto unpacking using **,

Output :

Another example,

Output:

Complete example is as follows,

Output:

 

Click Here to Subscribe for more Articles / Tutorials like this.