backlinks to this page:
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:
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  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