Packing and Unpacking Arguments in Python:

There is the use of two operators, * for tuples and ** for dictionaries in python for data science.

Introduction:

If we are in a situation where a function receives four arguments and we want to call this function and have a list size of 4 with us and these should carry all arguments. The call will not work if we pass the list to the function in this case.

Packing and Unpacking Arguments in Python for Data Science - PST

Unpacking:

Use * for unpacking the list which will see to it that all elements are pass as different parameters.

Packing and Unpacking Arguments in Python for Data Science - PST

In the example below, we will see the built-in range() function which expects start and stop arguments if these are not available in separate use the function call using * operator in order to unpack arguments out of a list or tuple.

Packing and Unpacking Arguments in Python for Data Science - PST

Packing:

When arguments passed to a Python function in data science are unknown, packing is used to pack all arguments in a Tuple.

Packing and Unpacking Arguments in Python for Data Science - PST

The function mySum() shown above does packing to pack all arguments the method call receives into a single variable. When we have the packed variable, we can perform all operations which we perform on a tuple. To get the first and second argument args[0] and args[1] is there. Tuples are not mutable, so, in order to change or delete or change the arrangement we need to change the tuple to a list. The args are converted to list.

Packing & Unpacking:

** in Dictionaries:

In the above example ** unpacked the dictionary that was there with the list and the items in the dictionary were passed as key arguments to function. So, instead of writing “fun(1, b=4, c=10)” we write “fun(1, **d)”.

Some Useful Points:
  1. Where we need to send a large number of requests to the server, socket programming is there.
  2. It is there to send variable arguments to view function in the Django network.
  3. Wrapper functions are available which allow us to pass in variable arguments.
  4. Argument modification is easy, but proper validation is not available. This is the reason it should be there with utmost care.

To learn more, you can check this and this.

Leave a Reply

Your email address will not be published. Required fields are marked *