Python · Tuples
Tuple Methods
The full text of this chapter, to read or revisit. To practise, do the exercises.
▶ Do the exercisesExercise 1 — Tuple Methods
Unlike lists, tuples are immutable, which means they have very few methods. In fact, tuples only have two built-in methods:
1.
count()
: Counts how many times a value appears in the tuple
2.
index()
: Finds the position of a value in the tuple
codemon_types = ("water", "fire", "plant", "water", "electric")
# Count how many water types we have
water_count = codemon_types.count("water")
print(f"Number of water types: {water_count}")
# Find the position of the first fire type
fire_position = codemon_types.index("fire")
print(f"Position of fire type: {fire_position}")
Be careful with index()
If the value doesn't exist in the tuple,
index()
will raise a ValueError. Always check if the value exists first, or use a try-except block.
Exercise 2 — Count Method
What will be the output of the following code?
team = ("Aquachu", "Pyrochu", "Florachu", "Aquachu")
print(team.count("Aquachu"))
Hint : Remember: The count() method returns the number of times a specified value appears in the tuple.
Exercise 3 — Finding an index
Complete the code to find the position of
"Pyrochu"
in the tuple.
team = ("Aquachu", "Pyrochu", "Florachu", "Aquachu")
# Find the position of Pyrochu
position = team.____("Pyrochu")
print(f"Pyrochu is at position {position}")
Options: index find position count
Hint : The index() method returns the first occurrence of the specified value.
Exercise 4 — The len() function with tuples
Another important built-in function to use with tuples is
len()
. It returns the number of items in the tuple.
team = ("Aquachu", "Pyrochu", "Florachu")
# Find out how many Codémon are in your team
team_size = len(team)
print(f"You have {team_size} Codémon in your team")
# An empty tuple
empty_team = ()
print(f"Empty team size: {len(empty_team)}")
Function vs Method
Note that
len()
is a function, not a method. You call it with the tuple as an argument:
len(tuple)
, not
tuple.len()
.
Exercise 5 — Tuple Length
What is the correct way to find the length of a tuple named
codemon_stats
?
Options
• ```len(codemon_stats)```
• ```codemon_stats.len()```
• ```codemon_stats.length()```
• ```codemon_stats.size()```
Hint : Remember: len() is a built-in function that takes the tuple as an argument, not a method of the tuple.
Exercise 6 — Converting to and from Tuples
You can convert other data types to tuples using the
tuple()
function, and convert tuples to other types like lists.
codemon_list = ["Aquachu", "Pyrochu", "Florachu"]
codemon_tuple = tuple(codemon_list)
print(f"Tuple from list: {codemon_tuple}")
# Convert a string to a tuple
name = "Aquachu"
name_tuple = tuple(name)
print(f"Tuple from string: {name_tuple}")
# Convert a tuple to a list
stats_tuple = (120, 45, 80)
stats_list = list(stats_tuple)
print(f"List from tuple: {stats_list}")
Why convert?
Converting between tuples and lists is useful when you need to either modify the data (use a list) or ensure it stays unchanged (use a tuple).
Exercise 7 — Convert and Modify
1. Turn the tuple into a list
2. Modify the list
3. Convert it back to a tuple
# tuple (HP, Attack, Defense)
stats = (100, 45, 80)
# Convert to a list to modify
stats_list = ____(stats)
print(stats_list)
# Change the data
stats_list[1] = stats_list[1] + 10
# Convert back to a tuple
new_stats = ____(stats_list)
print(new_stats)
Options: list tuple convert array
Hint : Remember: Tuples are immutable, if you want changes, you need a list.
Exercise 8 — Tuple Operations
Match each tuple operation with its description.
Items to match
• tuple.count(x)
• tuple.index(x)
• len(tuple)
• list(tuple)
Definitions
• Counts how many times x appears in the tuple
• Returns the position of the first occurrence of x
• Returns the number of items in the tuple
• Converts the tuple to a list
Exercise 9 — Built-in Functions with Tuples
Several Python built-in functions work well with tuples. Let's look at some common ones:
-
min()
: Finds the smallest element in a tuple.
-
max()
: Finds the largest element in a tuple.
-
sum()
: Calculates the sum of all elements in a tuple.
levels = (15, 8, 23, 7, 42)
# Find the min and max values
print(f"Lowest level: {min(levels)}")
print(f"Highest level: {max(levels)}")
# Calculate the sum
print(f"Total of all levels: {sum(levels)}")
Exercise 10 — Built-in Functions with Tuples
Match each function with its output for the tuple
stats = (45, 90, 10, 75)
.
Items to match
• min(stats)
• max(stats)
• sum(stats)
Exercise 11 — Stats Analyzer Challenge - Codémon Team Analysis
Welcome to the Stats Analyzer! You need to analyze your Codémon team's level data.
Your tasks:
1. Count how many times level 15 appears in the team and display it
2. Find the position (index) of the highest level (25) and display it
3. Display the total number of Codémon in the team
4. Convert the tuple to a list, increase the first Codémon's level by 5, then convert back to a tuple
5. Calculate and display the average level of the team
Starter code
print("=== TEAM STATS ANALYZER ===")
team_levels = (10, 15, 8, 15, 25, 12)
print(f"Team levels: {team_levels}")
# Task 1: Count how many times level 15 appears
# Task 2: Find the position of level 25
# Task 3: Display total number of Codémon
# Task 4: Convert to list, increase first level by 5, convert back
# Task 5: Calculate and display average level
Back to the course