Module 22: Advanced Tuple Practice

Deeper dive: Packing, unpacking, methods, nesting, and slicing tuples.

Tuple Packing & Unpacking

Python allows creating tuples without `()` (packing) and assigning tuple elements directly to variables (unpacking). Click the parts to understand.

# Packing (Parentheses optional)
point = 10, 20

# Unpacking (Assigning tuple elements to variables)
x, y = point

Identify all 8 parts!

Challenge: Given `data = ("Alpha", 101, True)`, write the code to unpack it into variables `name`, `id_num`, and `status`.

Tuple Methods: .index() & .count()

Tuples have few methods because they're immutable. Two useful ones are `.index(value)` (finds first occurrence) and `.count(value)` (counts occurrences). Try them out!

Demo Tuple: `items = ('A', 1, 'B', 2, 'A', 3, 'A')`
Result will appear here...

Nested Tuples & Slicing

Tuples can contain other tuples! Access nested elements using multiple indices. Slicing (`[start:end]`) works like lists, creating a *new* tuple.

matrix = ((1, 2), (3, 4))
element = matrix[1][0]  # Accesses the number 3

Challenge: Given `alphabet = ('a', 'b', 'c', 'd', 'e', 'f')`, write code to get a new tuple containing `('c', 'd', 'e')` using slicing.

Sliced tuple will appear here...

Tuples in Action: Function Returns

A common Python pattern is to return multiple values from a function using a tuple. Unpacking makes accessing these results clean and easy.

Scenario: Imagine a function `get_coordinates()` returns a tuple `(x, y, z)`.

# Assume function call returns a tuple result = get_coordinates() # result might be (15, -5, 10)

Challenge: Write the code to unpack the `result` tuple into variables `pos_x`, `pos_y`, and `pos_z`.

Advanced Mini Missions!

Combine your advanced tuple skills to complete these tasks.

Mission 1: Pack & Unpack Coordinates

Use tuple packing to create a `location` tuple with values "City Hall" and 123. Then, unpack `location` into `place` and `address_num` variables. Print both variables.

Mission 2: Find and Count

Create a tuple `grades = ('B', 'A', 'C', 'A', 'B', 'A')`. First, print how many times 'A' appears using `.count()`. Second, print the index of the *first* 'B' using `.index()`.

Mission 3: Nested Access & Slicing

Create `schedule = (("Mon", "Tue"), ("Wed", "Thu"), ("Fri",))`. First, access and print "Thu". Second, create and print a *slice* containing the first two inner tuples `(("Mon", "Tue"), ("Wed", "Thu"))`.

Module 22 Advanced Practice Complete!

Great job tackling these advanced tuple concepts! You're becoming proficient.
Review the basic practice or watch the video lesson if needed, or move on to the next module!