🔄 Quick Recap (Day 8)

  • You learned to create and manipulate lists: adding, removing, and accessing items.

  • You practiced with list_practice.py to reinforce those skills.

🎯 What You’ll Learn Today

  1. What a tuple is and how it differs from a list.

  2. How to create and access tuple items by index.

  3. The main tuple methods: count() and index().

  4. How to unpack a tuple into individual variables.

📖 What Is a Tuple?

A tuple is like a list, but once you create it, you cannot change its contents. This makes it perfect for storing data that must remain constant—like configuration values or (x, y) coordinates.

  • Immutable: you can’t add, remove, or change items after creation.

  • Ordered: items have a fixed position, starting at index 0.

Creating a Tuple

Use parentheses () and separate items with commas:

colors = ("red", "green", "blue")
print(colors)

Output:

('red', 'green', 'blue')

For a single-item tuple, include a comma after the item:

single = (42,)
print(type(single))  # <class 'tuple'>

📖 Accessing Tuple Items

Indexing

Like lists, tuples use zero-based indices:

print(colors[0])   # red
print(colors[2])   # blue
print(colors[-1])  # blue (last item)

Attempting to change an item raises an error:

colors[0] = "purple"  # TypeError: 'tuple' object does not support item assignment

📖 Tuple Methods

Tuples support two simple methods:

  • count(value): Returns how many times value appears.

  • index(value): Returns the index of the first occurrence of value.

numbers = (1, 2, 2, 3)
print(numbers.count(2))   # 2
print(numbers.index(3))   # 3 is at index 3

📖 Unpacking Tuples

You can extract tuple items into variables in one line:

point = (10, 20)
x, y = point
print(f"x={x}, y={y}")  # x=10, y=20

Unpacking must match the number of items:

# Wrong: too many variables
# a, b, c = point  # ValueError

đŸ§™â€â™‚ïž Take the Wand and Try Yourself

  1. Create a file named tuple_practice.py.

  2. Inside, define a tuple dimensions with three numbers (e.g., width, height, depth).

  3. Print:

    • The first dimension (dimensions[0]).

    • The last dimension (dimensions[-1]).

  4. Use count() to show how many times the middle dimension appears.

  5. Use index() to find the position of the largest dimension.

  6. Unpack dimensions into three variables (w, h, d) and print them.

Solution Example (tuple_practice.py):

# tuple_practice.py

dimensions = (10, 20, 10)

# Access by index
print("First:", dimensions[0])
print("Last:", dimensions[-1])

# Methods
print("Count of 10:", dimensions.count(10))
print("Index of max dimension:", dimensions.index(max(dimensions)))

# Unpacking
w, h, d = dimensions
print(f"Width={w}, Height={h}, Depth={d}")

Run:

python tuple_practice.py

Expected output:

First: 10
Last: 10
Count of 10: 2
Index of max dimension: 1
Width=10, Height=20, Depth=10

Once your output matches, you’ve mastered tuples!

Up next: Day 10: Dictionaries—learn how to store key-value pairs.

Keep Reading