01 - Calling Functions and Unpacking Tuples

Argument Passing to Functions in Python

Have you ever encountered code like this in Java:

   myObject.cook(12, 32.5, 200)

What do these arguments mean? A good IDE may let you hover over the arguments and see what the parameter names, but otherwise it is not very clear what each argument is instructing the function to do.

A very nice feature of Python is that it allows you to “name” arguments. Consider the following code:

def cook(salt, sugar, cookTemp):
    print("adding:", salt, " and ", sugar, 
        " sugar and will cook at ", cookTemp, "C")

salt = 12
cook(salt=salt, sugar=32.5, cookTemp=200)
cook(cookTemp=200, sugar=5, salt=15)

These functions calls are much clearer to read and in fact let you specify the arguments in any order.

Unpacking Lists/Tuples into Variables

Every wished you could easily have a function return more than one value? Well, Python makes this easier than other languages. Try running the following code:

1
2
3
4
def sqrcube(n):
    return n**2, n**3

print(sqrcube(2),sqrcube(3))

Technically, python is returning a tuple, which is basically an immutable list (here is a list of native Python datastructures). Tuples can be enclosed in parathesis (and sometimes this is required).

What type of variable do you use to receive the results of a function that returns data in this way? Here is a few examples:

def sqrcube(n):
    return n**2, n**3

both_values = sqrcube(2)
print(both_values[0],both_values[1])

nsquared, ncubed = sqrcube(2)
print(nsquared, ncubed)

Because Python autotypes variables, you do not need to worry about the type. In the first call, the function’s return value is stored directly in a tuple. The advantage here is that if your function returns a variable number of values, this works in all situations.

However, consider the case that your function always returns exactly 2 values. Then you can take the second approach, which is called unpacking. This is much more readable as you can assign meaningful names to the variables (instead of trying to recall what position 0 and 1 mean in the tuple).

References

Last modified April 21, 2024: Update deploy.yml (3125f7b)