0% found this document useful (0 votes)
2 views

Working with Tuples in Python

This lesson focuses on tuples in Python, highlighting their immutability, operations, and practical applications. Students will learn to use tuples for fixed data storage, return multiple values from functions, and utilize them as dictionary keys. The lesson includes examples, exercises, and discussions to reinforce understanding of tuples and their benefits in programming.

Uploaded by

hannnlady
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Working with Tuples in Python

This lesson focuses on tuples in Python, highlighting their immutability, operations, and practical applications. Students will learn to use tuples for fixed data storage, return multiple values from functions, and utilize them as dictionary keys. The lesson includes examples, exercises, and discussions to reinforce understanding of tuples and their benefits in programming.

Uploaded by

hannnlady
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

Working with Tuples in Python

Objectives: By the end of this lesson, students will be able to:

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.​

●​ Summarize the flow of execution in programs involving functions.​

●​ Discuss the implications of passing mutable objects to functions and potential


side effects.​

●​ Introduce tuple packing and unpacking, highlighting its role in data manipulation.​
2

●​ Explore tuple assignment with unpacking, showcasing its convenience and


efficiency.​

●​ Discuss tuples as return values, illustrating how functions can return multiple
values.​

●​ Demonstrate unpacking tuples as arguments to function calls, improving code


readability.​

●​ Introduce the while statement as an alternative loop construct.​

●​ Explore the concept of a listener loop and its applications.​

●​ 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.

Through engaging examples and collaborative discussions, the lesson highlights


how tuples integrate with loops, functions, and dictionaries, and how they enhance
modular, well-organized programming.

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

II.​ Tuple Operations

Python supports several operations for working with tuples:

●​ Indexing and slicing: Access individual elements or subsets.​

●​ Iteration: Loop through all elements in a tuple.​

●​ Concatenation and repetition: Combine or repeat tuples.​

●​ Membership testing: Check if an item exists in a tuple using in or not in.​

Example:

t = ("BTS", "BLACKPINK", "TWICE")​


print(t[1]) # Output: BLACKPINK​
for group in t:​
print(group)​

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.

III.​ Tuple Immutability

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

Sample Program Problem: Write a program to demonstrate an immutable sequence for


idol rankings and explain why you cannot update a ranking.

idol_ranks = ("BTS", "BLACKPINK", "EXO")​


try:​
idol_ranks[0] = "TXT"​
except TypeError as e:​
print("Error:", e)
7

Explanation: The tuple ensures data integrity. The program shows what happens when
modification is attempted.

🔐 Try and Except in Tuple Immutability


In Python, tuples are immutable, meaning you cannot change their elements once
created.

Here's what happens in the code:

idol_ranks = ("BTS", "BLACKPINK", "EXO")​


try:​
idol_ranks[0] = "TXT"​
except TypeError as e:​
print("Error:", e)

●​ The tuple idol_ranks contains three fixed group names.​

●​ The line idol_ranks[0] = "TXT" tries to replace "BTS" with "TXT", which is
not allowed.​

●​ Python throws a TypeError because tuples do not support item assignment.​

●​ The try block attempts the change.​

●​ The except block catches the error and prints an informative message.​

🧠 Why this is useful:


●​ It helps your program avoid crashing by handling errors gracefully.​

●​ It's a safe way to test risky operations.​

🗣️ Output:
Error: 'tuple' object does not support item assignment
8

✅ Summary:
●​ Tuples are read-only.​

●​ try and except allow error handling.​

●​ This is a good practice when working with fixed or critical data.​

IV. Tuple Assignment and Packing/Unpacking

Tuples support multiple assignment operations, allowing values to be packed into a


tuple or unpacked into separate variables. This enhances code readability and
functionality.

Example:

(bp, bts) = ("BLACKPINK", "BTS")​


bts, bp = bp, bts​
print(bts, bp) # Output: BLACKPINK BTS

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

Explanation: This uses packing/unpacking to simplify multiple return values and


improve readability.

V. Tuples and Functions

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

Explanation: Demonstrates working with a list of tuples and tuple unpacking in a


function return.

VI. Common Uses and Best Practices

Tuples are ideal when data should not change. They're memory-efficient and hashable,
making them useful for:

1. Fixed Data Storage

Tuples are perfect for storing fixed, unchangeable data, such as coordinates, dates, and
configurations, that should remain constant throughout the program.

Example:

# Storing coordinates as a tuple​


coordinates = (37.7749, -122.4194) # Latitude, Longitude for San
Francisco​
print(f"Latitude: {coordinates[0]}, Longitude: {coordinates[1]}")​

# Storing a fixed configuration for an app​
config = ("dark_mode", True, "en-US") # (theme, enabled, language)​
print(f"App Configuration: {config}")

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:

# Function that returns multiple values as a tuple​


def get_user_info():​
name = "Jisoo"​
11

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:

# Using a tuple as a dictionary key​


favorite_groups = {​
("BTS", "Jimin"): "Bias",​
("BLACKPINK", "Lisa"): "Bias",​
("TWICE", "Nayeon"): "Bias"​
}​

# Accessing values using the tuple keys​
print(favorite_groups[("BTS", "Jimin")]) # Output: Bias​
print(favorite_groups[("BLACKPINK", "Lisa")]) # Output: Bias
In this example, the tuple ("BTS", "Jimin") is used as a key in the dictionary, where
each key uniquely identifies a group-member pair and associates it with a value ("Bias").

Best Practices for Using Tuples:

1.​ Use Tuples for Fixed Data:

When you have data that should not be altered, such as configuration settings or
coordinates, tuples are the way to go.​
12

2.​ Use Tuples for Return Values

If your function needs to return multiple related values, tuples provide a simple
and effective solution for returning multiple items from a function.​

3.​ Use Tuples as Dictionary Keys

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?​

○​ What benefits does immutability bring?​

○​ When might immutability be a limitation?​

○​ K-pop example: Would you want an idol's birthdate to change in your


code?​

3.​ You’re designing a fan database app that stores debut dates. Would you use a
list or a tuple for each date? Why?​

○​ Think about what you want to protect in the data.​


Example: (\"BLACKPINK\", (8, \"August\", 2016)) — how does
the tuple help ensure accuracy?​

4.​ Tuple unpacking helps you extract values directly into variables.​

○​ How does this improve readability?​

○​ Can you think of a scenario where unpacking would simplify code that
deals with multiple idol statistics?​

5.​ Real-world use case​

○​ 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

Optional Activity (if time allows):

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:​

●​ Python documentation on tuples​

●​ Online coding platforms (e.g., Replit, Jupyter Notebook, google colab)​

You might also like