SoFunction
Updated on 2024-11-13

Python Variables Tutorial on Packing and Unpacking Parameters

Preface:

We use two operators * (for tuples) and ** (for dictionaries).

contexts

Consider the case where we have a function that takes four arguments. We want to call this function and we have a list of size 4 containing all the arguments of the function. If we just pass a list to the function, the call doesn't work.

# A Python program that demonstrates packing and unpacking requirements

# A sample function that takes 4 arguments and prints them.
def fun(a, b, c, d):
	print(a, b, c, d)

# Driver code
my_list = [1, 2, 3, 4]

# It doesn't work
fun(my_list)

Output :

TypeError: fun() takes exactly 4 arguments (1 given)

acrobatic display (esp. on horseback) (old)

package we can use ***** to unpack the list so that all its elements can be passed as distinct parameters.

# A sample function with 4 arguments that prints.
def fun(a, b, c, d):
	print(a, b, c, d)

# Driver code
my_list = [1, 2, 3, 4]

# Decompress the list into four parameters
fun(*my_list)

Output :

(1, 2, 3, 4)

We need to remember that the number of parameters must be the same length as the list we unwrap for the parameters.

# Error when len(args) ! = error when the actual arguments required by the function are not present

args = [0, 1, 4, 9]
def func(a, b, c):
	return a + b + c
# Calling functions with unwrapped parameters
func(*args)

Output:

Traceback (most recent call last):
  File "/home/", line 10, in <module>
    func(*args)
TypeError: func() takes 3 positional arguments but 4 were given

As another example, consider the built-in range() function that requires separate start and stop arguments. If they can't be used separately, write function calls using *-operator to unwrap the arguments from a list or tuple:

>>>
>>> range(3, 6) # Normal calls with separate parameters
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # Called with parameters unwrapped from a list
[3, 4, 5]

Packing 

When we don't know how many arguments we need to pass to a python function, we can use Packing to pack all the arguments into a tuple.

# Demonstrate the Python program used for packaging

# This function uses packing to aggregate an unknown number of arguments
def mySum(*args):
	return sum(args)

# Driver code
print(mySum(1, 2, 3, 4, 5))
print(mySum(10, 20))

Output:

15 
30

The above function mySum() performs a "packing" to pack all the arguments received by this method call into a variable. Once we have this "packed" variable, we can use it to do what we would do with a normal tuple. args[0] and args[1] will give you the first and second arguments, respectively. Since our tuples are immutable, you can convert the args tuple to a list so that you can also modify, delete, and rearrange the items in i.

Packing and unpacking

Here is an example showing packing and unpacking.

# A Python program to demonstrate packing and unpacking.

# A sample python function that takes three arguments and prints them
def fun1(a, b, c):
	print(a, b, c)

# Another example function.
# This is an example of packing. All arguments passed to fun2 are packed into the tuple *args.
def fun2(*args):

	# Convert the args tuple to a list so we can modify it
	args = list(args)

	# Modify parameters
	args[0] = 'Haiyong'
	args[1] = 'awesome'

	# Unpack the arguments and call fun1()
	fun1(*args)

# Driver code
fun2('Hello', 'beautiful', 'world!')

Output:

(Haiyong, awesome, world!)

For dictionaries

# Sample program demonstrating the use of ** unpacking dictionary entries
def fun(a, b, c):
	print(a, b, c)

# Unpacking dictionary calls
d = {'a':2, 'b':4, 'c':10}
fun(**d)

Output:

2 4 10

Here ** unpacks the dictionary used with it and passes the items in the dictionary as keyword arguments to the function. So writing "fun(1, **d)" is equivalent to writing "fun(1, b=4, c=10)".

# A Python program demonstrating the use of ** to package dictionary entries
def fun(**kwargs):

	# kwargs is a dictionary
	print(type(kwargs))

	# Print dictionary items
	for key in kwargs:
		print("%s = %s" % (key, kwargs[key]))

# Driver code
fun(name="geeks", ID="101", language="Python")

Output:

<class 'dict'>
name = geeks
ID = 101
language = Python

Applications and Essentials :

  • Used in socket programming to send a large number of requests to the server.
  • Used in the Django framework to send variable arguments to view functions.
  • Some wrapper functions require us to pass in variable parameters.
  • Parameters become easy to modify, but at the same time validate incorrectly, so they must be used with care.

This article on Python variable tutorial on packaging and unpacking parameters is introduced to this article, more related to Python packaging and unpacking parameters, please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!