Returning and unpacking tuples

This feature is often used when returning multiple values from a function. Here we make a function to return the minimum and maximum values of a sequence, the hard work being done by two built-in functions min() and max():

>>> def minmax(items):
... return min(items), max(items)
...
>>> minmax([83, 33, 84, 32, 85, 31, 86])
(31, 86)

Returning multiple values as a tuple is often used in conjunction with a wonderful feature of Python called tuple unpacking. Tuple unpacking is a so-called destructuring operation which allows us to unpack data structures into named references. For example, we can assign the result of our minmax() function to two new references like this:

>>> lower, upper = minmax([83, 33, 84, 32, 85, 31, 86])
>>> lower
31
>>> upper
86

This also works with nested tuples:

>>> (a, (b, (c, d))) = (4, (3, (2, 1)))
>>> a
4
>>> b
3
>>> c
2
>>> d
1

 

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset