5.3 Tuples

As discussed in the preceding chapter, tuples are immutable and typically store heterogeneous data, but the data can be homogeneous. A tuple’s length is its number of elements and cannot change during program execution.

Creating Tuples

To create an empty tuple, use empty parentheses:

In [1]: student_tuple = ()

In [2]: student_tuple
Out[2]: ()

In [3]: len(student_tuple)
Out[3]: 0

Recall that you can pack a tuple by separating its values with commas:

In [4]: student_tuple = 'John', 'Green', 3.3

In [5]: student_tuple
Out[5]: ('John', 'Green', 3.3)

In [6]: len(student_tuple)
Out[6]: 3

When you output a tuple, Python always displays its contents in parentheses. You may surround a tuple’s comma-separated list of values with optional parentheses:

In [7]: another_student_tuple = ('Mary', 'Red', 3.3)

In [8]: another_student_tuple
Out[8]: ('Mary', 'Red', 3.3)

The following code creates a one-element tuple:

In [9]: a_singleton_tuple = ('red',) # note the comma

In [10]: a_singleton_tuple
Out[10]: ('red',)

The comma (,) that follows the string 'red' identifies a_singleton_tuple as a tuple—the parentheses are optional. If the comma were omitted, the parentheses would be redundant, and a_singleton_tuple would simply refer to the string 'red' rather than a tuple.

Accessing Tuple Elements

A tuple’s elements, though related, are often of multiple types. Usually, you do not iterate over them. Rather, you access each individually. Like list indices, tuple indices start at 0. The following code creates time_tuple representing an hour, minute and second, displays the tuple, then uses its elements to calculate the number of seconds since midnight—note that we perform a different operation with each value in the tuple:

In [11]: time_tuple = (9, 16, 1)

In [12]: time_tuple
Out[12]: (9, 16, 1)

In [13]: time_tuple[0] * 3600 + time_tuple[1] * 60 + time_tuple[2]
Out[13]: 33361

Assigning a value to a tuple element causes a TypeError.

Adding Items to a String or Tuple

As with lists, the += augmented assignment statement can be used with strings and tuples, even though they’re immutable. In the following code, after the two assignments, tuple1 and tuple2 refer to the same tuple object:

In [14]: tuple1 = (10, 20, 30)

In [15]: tuple2 = tuple1

In [16]: tuple2
Out[16]: (10, 20, 30)

Concatenating the tuple (40, 50) to tuple1 creates a new tuple, then assigns a reference to it to the variable tuple1tuple2 still refers to the original tuple:

In [17]: tuple1 += (40, 50)

In [18]: tuple1
Out[18]: (10, 20, 30, 40, 50)

In [19]: tuple2
Out[19]: (10, 20, 30)

For a string or tuple, the item to the right of += must be a string or tuple, respectively—mixing types causes a TypeError.

Appending Tuples to Lists

You can use += to append a tuple to a list:

In [20]: numbers = [1, 2, 3, 4, 5]

In [21]: numbers += (6, 7)

In [22]: numbers
Out[22]: [1, 2, 3, 4, 5, 6, 7]

Tuples May Contain Mutable Objects

Let’s create a student_tuple with a first name, last name and list of grades:

In [23]: student_tuple = ('Amanda', 'Blue', [98, 75, 87])

Even though the tuple is immutable, its list element is mutable:

In [24]: student_tuple[2][1] = 85

In [25]: student_tuple
Out[25]: ('Amanda', 'Blue', [98, 85, 87])

In the double-subscripted name student_tuple[2][1], Python views student_tuple[2] as the element of the tuple containing the list [98, 75, 87], then uses [1] to access the list element containing 75. The assignment in snippet [24] replaces that grade with 85.

tick mark Self Check

  1. (True/False) A += augmented assignment statement may not be used with strings and tuples, because they’re immutable.
    Answer: False. A += augmented assignment statement also may be used with strings and tuples, even though they’re immutable. The result is a new string or tuple, respectively.

  2. (True/False) Tuples can contain only immutable objects.
    Answer: False. Even though a tuple is immutable, its elements can be mutable objects, such as lists.

  3. (IPython Session) Create a single-element tuple containing 123.45, then display it.
    Answer:

    In [1]: single = (123.45,)
    
    In [2]: single
    Out[2]: (123.45,)
  4. (IPython Session) Show what happens when you attempt to concatenate sequences of different types—the list [1, 2, 3] and the tuple (4, 5, 6)—using the + operator.
    Answer:

    In [3]: [1, 2, 3] + (4, 5, 6)
    -------------------------------------------------------------------------
    TypeError                               Traceback (most recent call last)
    <ipython-input-3-1ac3d3041bfa> in <module>()
    ----> 1 [1, 2, 3] + (4, 5, 6)
    
    TypeError: can only concatenate list (not "tuple") to list
..................Content has been hidden....................

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