13.1. Introduction

You have previously seen tuples, a sequence type that works just like lists except that they are immutable.

When working with multiple values or multiple variable names, the Python interpreter does some automatic packing and unpacking to and from tuples, which allows some simplifications in the code you write.

13.1.1. Learning Objectives

At the end of this chapter, you will be able to:

  • Recognize when code is using implicit tuple packing
  • Use implicit tuple packing to return multiple values from a function
  • Read and write code that unpacks a tuple into multiple variables

13.2. Tuple Packing

Wherever python expects a single value, if multiple expressions are provided, separated by commas, they are automatically packed into a tuple. For example, we could have omitted the parentheses when first assigning a tuple to the variable julia.

Check your understanding

    tuples-2-1: Which of the following statements will output Atlanta, Georgia
  • print(julia['city'])
  • julia is a tuple, not a dictionary; indexes must be integers.
  • print(julia[-1])
  • [-1] picks out the last item in the sequence.
  • print(julia(-1))
  • Index into tuples using square brackets. julia(-1) will try to treat julia as a function call, with -1 as the parameter value.
  • print(julia(6))
  • Index into tuples using square brackets. julia(-1) will try to treat julia as a function call, with -1 as the parameter value.
  • print(julia[7])
  • Indexing starts at 0. You want the seventh item, which is julia[6]
2. Create a tuple called practice that has four elements: ‘y’, ‘h’, ‘z’, and ‘x’.
3. Create a tuple named tup1 that has three elements: ‘a’, ‘b’, and ‘c’.
4. Provided is a list of tuples. Create another list called t_check that contains the third element of every tuple.
5. Below, we have provided a list of tuples. Write a for loop that saves the second element of each tuple into a list called seconds.
Next Section - 13.3. Tuples as Return Values