Tuples

Data Structures: Tuples

A tuple stores an ordered collection of items. Tuples are similar to lists, but they cannot be changed after creation.

This makes them useful for information that should remain fixed, such as the days of the week, a booking record, or the details returned by a function.

Creating Tuples

Create a tuple by separating items with commas. Parentheses () make the structure easier to read and are normally included.

languages = ("Python", "JavaScript", "R")

print(languages)
('Python', 'JavaScript', 'R')
print(type(languages))
<class 'tuple'>

Compare the syntax for a list and a tuple:

fruit_list = ["apple", "banana", "cherry"]

print(type(fruit_list))
<class 'list'>
fruit_tuple = ("apple", "banana", "cherry")

print(type(fruit_tuple))
<class 'tuple'>

One-item Tuples

A one-item tuple needs a trailing comma. Without the comma, Python treats the parentheses as ordinary grouping.

not_a_tuple = ("Python")
one_item_tuple = ("Python",)

print(type(not_a_tuple))
print(type(one_item_tuple))
<class 'str'>
<class 'tuple'>
Exercise: Spot the tuple

Before running the code, decide which variables contain tuples.

a = ("weekend")
b = ("weekend",)
c = "weekend",
d = ["weekend"]

b and c are tuples. The comma creates the tuple; parentheses are optional in many situations.

Properties of Tuples

Ordered

Tuples preserve the order of their items. Like lists, they use zero-based indexing and support negative indexes.

weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")

print(weekdays[0])
Monday
print(weekdays[-1])
Friday

Tuples also support slicing.

print(weekdays[1:4])
('Tuesday', 'Wednesday', 'Thursday')
print(weekdays[:2])
('Monday', 'Tuesday')

Duplicate Items

Tuples can contain the same value more than once.

survey_answers = ("yes", "no", "yes", "maybe", "yes")

print(survey_answers)
('yes', 'no', 'yes', 'maybe', 'yes')

Immutable

Tuples are immutable. Their items cannot be replaced, added, or removed after the tuple is created.

weekdays = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday")
weekdays[0] = "Sunday"
TypeError: 'tuple' object does not support item assignment

Immutability protects information from accidental changes. It also means that methods such as append(), remove(), and sort() are not available for tuples.

Exercise: Predict the output

Without running the code, write the two lines that it prints.

menu = ("soup", "salad", "pasta", "cake")

print(menu[-2])
print(menu[1:3])
pasta
('salad', 'pasta')

Tuple Operations

The + operator combines tuples, and * repeats them.

morning = ("coffee", "email")
afternoon = ("class", "study")

day_plan = morning + afternoon
print(day_plan)

reminders = ("stand up",) * 3
print(reminders)
('coffee', 'email', 'class', 'study')
('stand up', 'stand up', 'stand up')

The len() function returns the number of items.

print(len(day_plan))
4

The in operator checks whether an item is present.

print("class" in day_plan)
True
print("gym" in day_plan)
False

Tuple Methods

Because tuples are immutable, they have only two commonly used methods:

  • count() returns the number of times a value appears.
  • index() returns the index of the first matching value.
survey_answers = ("yes", "no", "yes", "maybe", "yes")

print(survey_answers.count("yes"))
3
print(survey_answers.index("maybe"))
3
Exercise: Analyze a vote

Use tuple methods to print:

  1. The number of votes for "film".
  2. The index of the first vote for "games".
votes = ("music", "film", "games", "film", "film", "music")
votes = ("music", "film", "games", "film", "film", "music")

print(votes.count("film"))
print(votes.index("games"))

Packing and Unpacking

Creating a tuple is sometimes called packing because several values are packed into one object.

booking = ("Aisha Khan", "Madrid", "18:45")

print(booking)
('Aisha Khan', 'Madrid', '18:45')

Unpacking assigns each item to a separate variable.

passenger, destination, departure_time = booking

print(passenger)
print(destination)
print(departure_time)
Aisha Khan
Madrid
18:45

The number of variables must match the number of tuple items.

Exercise: Unpack a media record

Unpack the tuple into the variables title, creator, and year. Then print this sentence:

Spirited Away was created by Hayao Miyazaki in 2001.
film = ("Spirited Away", "Hayao Miyazaki", 2001)
film = ("Spirited Away", "Hayao Miyazaki", 2001)
title, creator, year = film

print(f"{title} was created by {creator} in {year}.")

Converting Between Lists and Tuples

Use list() when a tuple needs to be changed. After editing it, use tuple() to convert it back.

route = ("Lisbon", "Paris", "Berlin")

editable_route = list(route)
editable_route.append("Prague")
route = tuple(editable_route)

print(route)
('Lisbon', 'Paris', 'Berlin', 'Prague')
Exercise: Fix the itinerary

The itinerary was stored as a tuple, but "Rome" must be replaced with "Florence". Complete the update by converting between data structures.

itinerary = ("Milan", "Rome", "Venice")
itinerary = ("Milan", "Rome", "Venice")

editable_itinerary = list(itinerary)
editable_itinerary[1] = "Florence"
itinerary = tuple(editable_itinerary)

print(itinerary)

Returning Multiple Values

A function can return several values as a tuple.

def describe_title(title):
    cleaned_title = title.strip().title()
    character_count = len(cleaned_title)
    return cleaned_title, character_count


book_title, title_length = describe_title("  the left hand of darkness  ")

print(book_title)
print(title_length)
The Left Hand Of Darkness
25
Exercise: Event summary

Write a function named event_summary() that receives an event name and a city. It should return both values with title case applied. Unpack the result and print it.

Example call:

event, city = event_summary("design week", "barcelona")
def event_summary(event_name, city_name):
    return event_name.title(), city_name.title()


event, city = event_summary("design week", "barcelona")

print(event)
print(city)

Challenge: Library record

Create a tuple named book containing a title, an author, and a publication year. Then:

  1. Unpack the tuple into three variables.
  2. Print a complete sentence using those variables.
  3. Print the number of items in the tuple.
  4. Check whether the author’s name appears in the tuple.
book = ("Kindred", "Octavia Butler", 1979)
title, author, year = book

print(f"{title} was written by {author} and published in {year}.")
print(len(book))
print(author in book)

Lists and Tuples Compared

Data structure Syntax Ordered Mutable Duplicates
List [] Yes Yes Yes
Tuple () Yes No Yes

Use a list when the collection may change. Use a tuple when the collection should remain fixed.

Summary

  • Tuples usually use parentheses: ().
  • A one-item tuple requires a trailing comma.
  • Tuples are ordered and immutable.
  • Tuples support indexing, slicing, count(), and index().
  • Tuple unpacking assigns items to separate variables.
  • Functions can return multiple values in a tuple.

Homework and Review

Work through the “Lists” and “Tuples” homework exercises available here. To earn participation credit, complete the exercises highlighted in red.

Lists Tuples