đ Quick Recap (Day 8)
You learned to create and manipulate lists: adding, removing, and accessing items.
You practiced with
list_practice.pyto reinforce those skills.
đŻ What Youâll Learn Today
What a tuple is and how it differs from a list.
How to create and access tuple items by index.
The main tuple methods:
count()andindex().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 timesvalueappears.index(value): Returns the index of the first occurrence ofvalue.
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=20Unpacking must match the number of items:
# Wrong: too many variables
# a, b, c = point # ValueErrorđ§ââïž Take the Wand and Try Yourself
Create a file named
tuple_practice.py.Inside, define a tuple
dimensionswith three numbers (e.g., width, height, depth).Print:
The first dimension (
dimensions[0]).The last dimension (
dimensions[-1]).
Use
count()to show how many times the middle dimension appears.Use
index()to find the position of the largest dimension.Unpack
dimensionsinto 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.pyExpected output:
First: 10
Last: 10
Count of 10: 2
Index of max dimension: 1
Width=10, Height=20, Depth=10Once your output matches, youâve mastered tuples!
Up next: Day 10: Dictionariesâlearn how to store key-value pairs.