Introduction to Tuples

The full text of this chapter, to read or revisit. To practise, do the exercises.

▶ Do the exercises

Exercise 1 — What are Tuples?

A tuple is an ordered, immutable collection of elements. In simple terms, it's like a list that cannot be changed after creation.

Tuples are created using parentheses () or the tuple() constructor. Here are some examples:

codemon_team = ("Aquachu", "Pyrochu", "Florachu") print(type(codemon_team), codemon_team) codemon_levels = tuple([5, 7, 3]) print(type(codemon_levels), codemon_levels) empty_tuple = () print(type(empty_tuple), empty_tuple)

Creating a tuple with one element

To create a tuple with just one element, you must include a trailing comma after the element. Without the comma, Python treats it as a regular value in parentheses. Example: single_element = (42,) # This is a tuple Not a tuple: just_a_number = (42) # This is just an integer

# A single element tuple - note the comma! single_codemon = ("Aquachu",) print(single_codemon, type(single_codemon)) # Without the comma - this is NOT a tuple not_a_tuple = ("Aquachu") print(not_a_tuple, type(not_a_tuple))

Exercise 2 — Creating Valid Tuples

Which of the following correctly creates a tuple with a single value of 5?

Options
• (5,)
• (5)
• tuple(5)
• [5]

Hint : Remember: To create a single-element tuple, you need a trailing comma after the element. tuple(5) will create an error because it tries to convert the integer 5 into a tuple, which is not valid.

Exercise 3 — Accessing Tuple Elements

You can access elements in a tuple using indexing, just like with lists. Remember that indexing starts at 0 in Python.

codemon_team = ("Aquachu", "Pyrochu", "Florachu") # Access the first element (index 0) first_codemon = codemon_team[0] print("First Codémon:", first_codemon) # Access the second element (index 1) second_codemon = codemon_team[1] print("Second Codémon:", second_codemon) # Access the last element (index -1) last_codemon = codemon_team[-1] print("Last Codémon:", last_codemon)

You can also use slicing to access a range of elements in a tuple:

codemon_stats = ("Aquachu", 10, 50, 30, 20) # Get elements from index 1 to 3 (exclusive) print(codemon_stats[1:4]) # Output: (10, 50, 30) # Get all elements from index 2 to the end print(codemon_stats[2:]) # Output: (50, 30, 20) # Get all elements from the beginning to index 3 (exclusive) print(codemon_stats[:3]) # Output: ('Aquachu', 10, 50)

Exercise 4 — Accessing Tuple Elements Practice

Complete the code to access the correct elements from the Codémon team tuple: 1. Get the first Codémon 2. Get the last Codémon using negative index 3. Get the second and third Codémon

Hint : Remember: Indexing starts at 0, negative indices count from the end, and slices use start:end format where end is exclusive.

Exercise 5 — Tuple Packing and Unpacking

Tuple packing is when you assign multiple values to a single tuple. Tuple unpacking is when you assign the elements of a tuple to multiple variables in a single operation.

# Tuple packing codemon_data = "Aquachu", 10, "Water", 50 print(codemon_data) print(type(codemon_data)) # Tuple unpacking name, level, element, hp = codemon_data print("Name:", name) print("Level:", level) print("Element:", element) print("HP:", hp)

Notice how we created a tuple without using parentheses? That's called tuple packing.

Tuple unpacking is particularly useful for swapping values

# Swapping values using tuple unpacking a = 5 b = 10 print("Before swap: a =", a, "b =", b) # Swap values a, b = b, a # This is actually tuple packing and unpacking! print("After swap: a =", a, "b =", b)

Exercise 6 — Tuple Unpacking Practice

Complete the code to unpack the Codémon stats tuple into the appropriate variables.

Hint : Remember: When unpacking a tuple, you need the same number of variables as elements in the tuple.

Exercise 7 — Tuple Immutability

One of the key characteristics of tuples is that they are immutable. This means that once a tuple is created, its elements cannot be changed, added, or removed.

If you need to modify a tuple, you'll have to create a new one:

codemon_team = ("Aquachu", "Pyrochu", "Florachu") print("Original tuple:", codemon_team) # Create a new tuple with a modified first element new_team = ("Zap",) + codemon_team[1:] print("New tuple:", new_team)

However, if a tuple contains mutable objects like lists, the contents of those objects can be changed:

# Tuple containing a mutable object (list) codemon_with_moves = ("Pyrochu", ["Ember", "Tackle"]) print("Original tuple with list:", codemon_with_moves) # We can modify the list inside the tuple codemon_with_moves[1].append("Flame Charge") print("After modifying the list inside:", codemon_with_moves)

When to use tuples vs lists

Use tuples when: - You need an immutable sequence - You want to store a collection of heterogeneous data (data of different types or different goal) - You want to ensure data integrity (can't be accidentally modified) Use lists when: - You need a collection that might change (add/remove elements) - You want to sort or modify elements frequently - You're working with homogeneous data that requires frequent manipulation

Exercise 8 — Tuple Operations and Results

Match each tuple operation with its correct result.

Items to match
• (1, 2) + (3, 4)
• ("Aquachu",) * 3
• len((10, 20, 30, 40))
• 5 in (5, 10, 15)
Definitions
• (1, 2, 3, 4)
• ("Aquachu", "Aquachu", "Aquachu")
• 4
• True

Exercise 9 — Tuples vs Lists

Which of the following statements about tuples and lists is FALSE?

Options
• Tuples can be modified after creation, just like lists.
• Tuples are defined using parentheses (), while lists use square brackets [].
• Tuples can be indexed and sliced just like lists.
• Tuples have a length just like lists.

Hint : Remember: The key difference between tuples and lists is that tuples are immutable - they cannot be changed after creation.

Exercise 10 — Understanding Tuple Immutability

Given the following code, which operation would cause an error?

codemon_data = ("Aquachu", ["Water Gun", "Bubble"], 15)
Options
• codemon_data[0] = "Pyrochu"
• codemon_data[1].append("Surf")
• print(codemon_data[2])
• new_data = codemon_data + ("Water",)

Hint : Remember: You cannot modify the tuple itself (changing, adding, or removing elements directly), but you can modify mutable objects contained within the tuple.

Exercise 11 — Battle Arena Challenge - Codémon Stats Manager

Welcome to the Battle Arena! You need to manage your Codémon's battle data using tuples. Your tasks: 1. Create a tuple called codemon with: name "Aquachu" and level 5 2. Unpack the tuple into separate variables (name, level) and display them 3. Create a list called attacks with two attacks: "Water Gun" and "Bubble" 4. Create a new tuple called codemon_with_attacks that contains the name, level, and the attacks list 5. Add a new attack "Surf" to the attacks list inside the tuple and display the final result

Starter code
print("=== BATTLE ARENA ===") # Task 1: Create codemon tuple (name, level) # Task 2: Unpack and display # Task 3: Create attacks list with "Water Gun" and "Bubble" # Task 4: Create codemon_with_attacks tuple (name, level, attacks) # Task 5: Add "Surf" to the attacks list and display result
Back to the course