Working with Tuples in Python
Working with Tuples in Python
1. Understand and explain the concept of tuples and how they differ from lists in
Python.
2. Apply tuple operations such as indexing, slicing, iteration, and concatenation in
real-world examples.
3. Demonstrate the immutability of tuples and handle related exceptions using
try/except.
4. Use tuples effectively in functions to return and receive multiple values.
5. Implement tuple packing and unpacking for more readable and efficient code.
6. Apply tuples as dictionary keys and understand their value in preserving
structured data.
Lesson Overview:
● Illustrate how functions can call other functions, demonstrating code modularity
and organization.
● Introduce tuple packing and unpacking, highlighting its role in data manipulation.
2
● Discuss tuples as return values, illustrating how functions can return multiple
values.
● Discuss the use of break and continue statements for loop control.
● Address the potential for infinite loops and strategies to avoid them.
Introduction
Tuples are one of Python’s core data types and serve as an essential tool for
organizing and managing fixed collections of values. Unlike lists, tuples are
immutable—once created, their contents cannot be changed—making them ideal for
representing structured, reliable data such as coordinates, records, and return values
from functions. In this lesson, students will explore tuples from both a practical and
conceptual perspective, learning how they contribute to safe, readable, and efficient
Python code.
I. Tuples
Tuples are a fundamental sequence type in Python, similar to lists, but with one key
difference: they are immutable. This means once a tuple is created, its elements cannot
3
be changed. Tuples are often used when a fixed collection of items is needed, and the
integrity of those values should be preserved.
Tuples are created by placing elements within parentheses (), separated by commas.
However, parentheses are optional, and simply using commas is sufficient.
Example:
t = (1, 2, 3)
print(type(t)) # Output: <class 'tuple'>
This tuple t contains three integer elements. Tuples are particularly useful for
representing fixed groups of items, such as RGB color codes or coordinates.
Sample Program Problem: Write a program that stores the birthdates (day, month, year)
of three K-pop idols in tuples and prints each one in a formatted sentence.
idols = [
("Lisa (BLACKPINK)", (27, "March", 1997)),
("Jungkook (BTS)", (1, "September", 1997)),
("Jisoo (BLACKPINK)", (3, "January", 1995))
]
for name, (day, month, year) in idols:
print(f"{name} was born on {day} {month}, {year}.")
Explanation: Each tuple stores structured, unchanging data. The for loop demonstrates
tuple unpacking.
4
Example:
This shows how indexing starts at 0 and how tuples can be easily traversed using loops.
# Tuple Operations
# 1. Indexing and Slicing: Access individual elements or subsets.
# Here, we access the second item in the tuple using indexing.
t = ("BTS", "BLACKPINK", "TWICE")
print(t[1]) # Output: BLACKPINK
# 2. Iteration: Loop through all elements in a tuple.
# The following for loop iterates through the tuple and prints each
group.
for group in t:
print(group)
# 3. Concatenation and Repetition: Combine or repeat tuples.
# Concatenating two tuples into one and printing the result.
t2 = ("EXO", "SEVENTEEN")
5
combined = t + t2
print(combined) # Output: ('BTS', 'BLACKPINK', 'TWICE', 'EXO',
'SEVENTEEN')
# Repeating a tuple by multiplying it.
repeated = t * 2
print(repeated) # Output: ('BTS', 'BLACKPINK', 'TWICE', 'BTS',
'BLACKPINK', 'TWICE')
# 4. Membership Testing: Check if an item exists in a tuple.
# Using 'in' to check if a group is in the tuple.
if "BTS" in t:
print("BTS is in the tuple!") # Output: BTS is in the tuple!
else:
print("BTS is not in the tuple.")
# Using 'not in' to check if an item is not in the tuple.
if "SEVENTEEN" not in t:
print("SEVENTEEN is not in the tuple!") # Output: SEVENTEEN is
not in the tuple!
else:
print("SEVENTEEN is in the tuple.")
Indexing and Slicing: The t[1] accesses the second item in the tuple.
Iteration: The for group in t loop goes through each element of the tuple t
and prints it.
Concatenation and Repetition: The + operator combines two tuples, and the *
operator repeats the tuple.
Membership Testing: The in and not in keywords check if a value exists in the
tuple.
6
Sample Program Problem: Write a function that counts how many K-pop group names
have more than 5 characters.
def count_long_names(groups):
count = 0
for name in groups:
if len(name) > 5:
count += 1
return count
group_names = ("BTS", "BLACKPINK", "EXO", "REDVELVET")
print("Groups with long names:", count_long_names(group_names))
Explanation: Demonstrates tuple iteration and use of a function with a for loop.
A key feature of tuples is that they are immutable. This means that once a tuple is
created, you cannot change its contents. This immutability makes tuples safer to use in
contexts where accidental modification must be avoided.
Example:
t = ("BTS", "BLACKPINK")
t[0] = "TXT" # TypeError
Explanation: The tuple ensures data integrity. The program shows what happens when
modification is attempted.
● The line idol_ranks[0] = "TXT" tries to replace "BTS" with "TXT", which is
not allowed.
● The except block catches the error and prints an informative message.
🗣️ Output:
Error: 'tuple' object does not support item assignment
8
✅ Summary:
● Tuples are read-only.
Example:
Sample Program Problem: Create a function that receives a tuple of three album sales
and returns the highest and average sales.
def album_summary(sales):
highest = max(sales)
average = sum(sales) / len(sales)
return highest, average
blackpink_sales = (800000, 1200000, 950000)
h, avg = album_summary(blackpink_sales)
print(f"Highest: {h}, Average: {avg:.2f}")
9
Tuples are useful when returning multiple values from a function. Rather than returning
a list, returning a tuple communicates that the returned values should be treated as a
group and remain unchanged.
Example:
def min_max_fandom(numbers):
return (min(numbers), max(numbers))
result = min_max_fandom([900000, 1300000, 650000])
print(result) # Output: (650000, 1300000)
Sample Program Problem: Write a function that takes in names and streaming counts
of K-pop groups as tuples and returns the group with the highest count.
def top_streamed(data):
top = data[0]
for group in data[1:]:
if group[1] > top[1]:
top = group
return top
streams = [("BTS", 1500000000), ("BLACKPINK", 1200000000), ("TWICE",
900000000)]
name, count = top_streamed(streams)
print(f"Top streamed group: {name} with {count} streams")
10
Tuples are ideal when data should not change. They're memory-efficient and hashable,
making them useful for:
Tuples are perfect for storing fixed, unchangeable data, such as coordinates, dates, and
configurations, that should remain constant throughout the program.
Example:
2. Function Returns
Tuples are often used to return multiple values from a function. This makes it easier to
work with multiple pieces of related data in one return statement.
Example:
age = 25
country = "South Korea"
return name, age, country # Tuple returned
# Calling the function
user_info = get_user_info()
print(user_info) # Output: ('Jisoo', 25, 'South Korea')
# Unpacking the returned tuple
name, age, country = user_info
print(f"Name: {name}, Age: {age}, Country: {country}")
3. Dictionary Keys
Tuples are hashable, making them suitable to be used as dictionary keys, unlike lists.
This is beneficial for organizing data where the keys should remain constant.
Example:
When you have data that should not be altered, such as configuration settings or
coordinates, tuples are the way to go.
12
If your function needs to return multiple related values, tuples provide a simple
and effective solution for returning multiple items from a function.
Since tuples are hashable, they can be used as keys in a dictionary to create
complex key-value pairs that require fixed data structures.
Sample Program Problem: Create a dictionary of group name and founding year as
tuple keys and fandom names as values.
groups = {
("BTS", 2013): "ARMY",
("BLACKPINK", 2016): "BLINK",
("EXO", 2012): "EXO-L"
}
for (group, year), fandom in groups.items():
print(f"{group} debuted in {year} and their fandom is called
{fandom}.")
Explanation: Shows tuples as immutable keys in dictionaries, pairing fixed identity with
metadata.
Discussion Questions
After exploring tuples through K-pop-inspired examples, discuss the following in pairs or
small groups. Share takeaways with the class.
1. Why do you think Python includes both lists and tuples?
○ Think about the differences between mutable and immutable data types.
13
○ K-pop tie-in: When managing group members versus their debut dates,
which structure feels more appropriate for each?
2. Tuples are immutable. How does this affect your approach to coding?
3. You’re designing a fan database app that stores debut dates. Would you use a
list or a tuple for each date? Why?
4. Tuple unpacking helps you extract values directly into variables.
○ Can you think of a scenario where unpacking would simplify code that
deals with multiple idol statistics?
○ Can you come up with an example (in K-pop or otherwise) where returning
multiple values from a function in a tuple makes sense?
○ For example: A function that returns a group's top song, total streams, and
chart rank.
14
Practice Exercise: Write a function that accepts a list of streaming numbers and
returns the lowest, highest, and average as a tuple.
Example:
def analyze_streams(streams):
return (min(streams), max(streams), sum(streams)/len(streams))
print(analyze_streams([1500000000, 1200000000, 900000000])) #
Output: (900000000, 1500000000, 1200000000.0)
● This exercise reinforces the idea of grouping related values into a tuple,
promoting efficient and safe data handling.
Resources: