Packing and Unpacking Advanced

Packing and Unpacking Advanced

·

2 min read

Why pack/unpack?

args and *args are used A LOT in functions. Not only packing but unpacking certain data types in functions and using them is really helpful. For instance, let's say that function A requires 30 variables. Without unpacking, you would have to type each variable 30 times into the function. Of course, the code wouldn't be concise as much and it will be easy to make mistakes. With unpacking, you can easily access a specific part of the user input of a function and of course, this would make the code more concise and easier to read.

Packing

x, y, *rest = range(1001)

Here, x and y will each be 0 and 1, and *rest will be packed as a list of numbers from 2 to 1000. This is very convenient and easy to do. However, packing is not used as much in python as unpacking.

Unpacking

def odd_chars(*args):
    for v in args:
        if ord(v) % 2:
            print(v)

odd_chars('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j')

Now here, it's more simple than assigning each input to a variable and checking each of them: it would also limit the number of inputs the function can take.

Example of a function WITHOUT unpacking

def odd_chars(a, b, c, d, e, f, g, h, i):
    if ord(a) % 2:
        print(a)
    if ord(b) % 2:
        print(b)
    and so on

Happy Coding!