GEOG 489
Advanced Python Programming for GIS

1.4.4 Multiple return values

PrintPrint

It happens quite often that you want to hand back different things as the result of a function, for instance four coordinates describing the bounding box of a polygon. But a function can only have one return value. It is common practice in such situations to simply return a tuple with the different components you want to return, so in this case a tuple with the four coordinates. Python has a useful mechanism to help with this by allowing us to assign the elements of a tuple (or other sequences like lists) to several variables in a single assignment. Given a tuple t = (12,3,2,2), instead of writing

top = t[0] 

left = t[1] 

bottom = t[2] 

right = t[3] 

you can write

top, left, bottom, right = t 

and it will have the exact same effect. The following example illustrates how this can be used with a function that returns a tuple of multiple return values. For simplicity, the function computeBoundingBox() in this example only returns a fixed tuple rather than computing the actual tuple values from a polygon given as input parameter.

def computeBoundingBox(): 

     return (12,3,41,32) 

 

top, left, bottom, right = computeBoundingBox() # assigns the four elements of the returned tuple to individual variables

print(top)    # output: 12

This section has been quite theoretical, but you will often encounter the constructs presented here when reading other people’s Python code and also in the rest of this course.