5.3 Tuples

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
  • 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.
  • Parentheses are optional when creating a tuple.
In [7]:
another_student_tuple = ('Mary', 'Red', 3.3)
In [8]:
another_student_tuple
Out[8]:
('Mary', 'Red', 3.3)
  • A comma is required to create a one-element tuple.
In [9]:
a_singleton_tuple = ('red',)  # note the comma
In [10]:
a_singleton_tuple
Out[10]:
('red',)

Accessing Tuple Elements

  • You generally access tuple elements directly rather than iterating over them.
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

Adding Items to a String or Tuple

  • += can be used with strings and tuples, even though they’re immutable.
  • Creates new objects.
In [14]:
tuple1 = (10, 20, 30)
In [15]:
tuple2 = tuple1
In [16]:
tuple2
Out[16]:
(10, 20, 30)
In [17]:
tuple1 += (40, 50)
In [18]:
tuple1   
Out[18]:
(10, 20, 30, 40, 50)
In [19]:
tuple2  
Out[19]:
(10, 20, 30)

Appending Tuples to Lists

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

In [23]:
student_tuple = ('Amanda', 'Blue', [98, 75, 87])
In [24]:
student_tuple[2][1] = 85
In [25]:
student_tuple
Out[25]:
('Amanda', 'Blue', [98, 85, 87])

©1992–2020 by Pearson Education, Inc. All Rights Reserved. This content is based on Chapter 5 of the book Intro to Python for Computer Science and Data Science: Learning to Program with AI, Big Data and the Cloud.

DISCLAIMER: The authors and publisher of this book have used their best efforts in preparing the book. These efforts include the development, research, and testing of the theories and programs to determine their effectiveness. The authors and publisher make no warranty of any kind, expressed or implied, with regard to these programs or to the documentation contained in these books. The authors and publisher shall not be liable in any event for incidental or consequential damages in connection with, or arising out of, the furnishing, performance, or use of these programs.