python packing/unpacking explained
In Python the term packing refers to grouping multiple values using the packing * operator.
For example:
def my_function(a, b, *args):
#args is a tuple of values
print("everything else: ", args)
# Output:
# my_function(1, 2, 500, 899)
# everything else: (500, 899)In the above example args is a tuple of values that you can use to dynamically accept a variable amount of function arguments.
You can also pack the key/value pairs into a dictionary:
def my_function(a, b, **kwargs):
#kwargs is a dictionary of key/values
print("everything else: ", kwargs)
# Output:
# my_function(1, 2, a=500, b=899)
# everything else: {'a': 500, 'b': 899}What about unpacking?
first, second = ["a", "b"]
print(first, second)
# a bNote that if you try to unpack the wrong number of variables an exception is raised, to fix that let's try combining unpacking with packing:
first, second, *other = ["a", "b", "c", "d"]
print(first, second, other)
# a b ['c', 'd']