The Python Game Book

code games. learn Python.

User Tools

Site Tools


Sidebar

Github:

en:glossary:p:packing

packing and unpacking of arguments

arguments of a function or class can be packed and unpacked using the asterix (*). dictionaries can be packed / unpacked using a double asterix (**).

This is useful for:

  • converting a list or tuble into a sequence of arguments (unpacking)
  • converting a sequence of arguments into a list (packing)

examples:

the python function sum() calculates the sum of an iterable (like a list). The iterable can have any number of items. However, the function itself only accept one single argument, the iterable. In the example below, a user-defined function calculate_sum() is written that takes any number of arguments (*args). The arguments must be numbers and can not be a list. By using unpacking, a list is converted into arguments

>>> sum(1,2,4) # does not work, sum accepts only one argument
Traceback (most recent call last):
  File "<pyshell#0>", line 1, in <module>
    sum(1,2,4)
TypeError: sum() takes at most 2 arguments (3 given)
>>> sum([1,2,3,4])  # works
10
>>> def calculate_sum(*args):
	total = 0
	print("the sum of ", list(args), "is: ", end="")
	for a in args:
		total += a
	return total

>>> calculate_sum(4)
the sum of [4] is: 4
>>> calculate_sum(1,2,3,4,5)
the sum of [1,2,3,4,5] is: 15
>>> calculate_sum([1,2,3]) # does not work, argument can not be a list
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    calculate_sum([1,2,3])
  File "<pyshell#7>", line 4, in calculate_sum
    total += a
TypeError: unsupported operand type(s) for +=: 'int' and 'list'
>>> calculate_sum(*[1,2,3]) # now it works by using packing
the sum of [1,2,3] is: 6

en/glossary/p/packing.txt · Last modified: 2020/10/13 07:24 by horst