Python Tuples
Master ordered, immutable collections in Python
📦 Understanding Tuples
Tuples are ordered, immutable (unchangeable) collections of items. Once a tuple is created, you cannot change its elements. They are often used to store related pieces of information that should not be modified.
# Creating tuples
empty_tuple = () # Empty tuple
single_item = (1,) # oneitem tuple (comma!)
numbers = (1, 2, 3) # Tuple of numbers
mixed = (1, "hello", True, 3.14) # Mixed data types
Creating Tuples
Tuples are created using parentheses
()
, with items separated by commas.
🔹 Empty Tuple
empty_tuple = ()
print(f"Empty tuple: {empty_tuple}") # Output: Empty tuple: ()
🔹 Tuple of Numbers
numbers = (1, 2, 3, 4, 5)
print(f"Numbers tuple: {numbers}") # Output: Numbers tuple: (1, 2, 3, 4, 5)
🔹 Tuple of Strings
fruits = ("apple", "banana", "cherry")
print(f"Fruits tuple: {fruits}") # Output: Fruits tuple: ('apple', 'banana', 'cherry')
🔹 Mixed Data Types Tuple
mixed_tuple = (1, "hello", True, 3.14)
print(f"Mixed tuple: {mixed_tuple}") # Output: Mixed tuple: (1, 'hello', True, 3.14)
🔹 Single Item Tuple
# Note: Single item tuple needs a comma!
single_item_tuple = ("hello",)
print(f"Single item tuple: {single_item_tuple}") # Output: Single item tuple: ('hello',)
Accessing Tuple Items
Tuple items are accessed by their index, similar to lists, starting from
0
. Negative indexing also works.
my_tuple = ("apple", "banana", "cherry", "orange", "kiwi")
# Accessing the first item (index 0)
print(f"First item: {my_tuple[0]}") # Output: First item: apple
# Accessing the third item (index 2)
print(f"Third item: {my_tuple[2]}") # Output: Third item: cherry
# Accessing the last item (index -1)
print(f"Last item: {my_tuple[-1]}") # Output: Last item: kiwi
Slicing Tuples
You can access a range of items in a tuple by using the slicing operator
:
, just like with lists.
my_tuple = ("apple", "banana", "cherry", "orange", "kiwi", "melon", "mango")
# Slice from index 2 to 5 (exclusive of 5)
print(f"Slice [2:5]: {my_tuple[2:5]}") # Output: Slice [2:5]: ('cherry', 'orange', 'kiwi')
# Slice from the beginning to index 4 (exclusive of 4)
print(f"Slice [:4]: {my_tuple[:4]}") # Output: Slice [:4]: ('apple', 'banana', 'cherry', 'orange')
# Slice from index 3 to the end
print(f"Slice [3:]: {my_tuple[3:]}") # Output: Slice [3:]: ('orange', 'kiwi', 'melon', 'mango')
# Slice with a step (every second item)
print(f"Slice [::2]: {my_tuple[::2]}") # Output: Slice [::2]: ('apple', 'cherry', 'kiwi', 'mango')
Immutability of Tuples
The key characteristic of tuples is their immutability. Once created, you cannot change, add, or remove items directly.
Cannot Modify
Direct modification raises TypeError
# This will cause an error
my_tuple = ("apple", "banana", "cherry")
# my_tuple[1] = "grape" # TypeError!
Workaround
Convert to list, modify, convert back
# Convert to list, modify, convert back
my_tuple = ("apple", "banana", "cherry")
my_list = list(my_tuple)
my_list[1] = "grape"
my_tuple = tuple(my_list)
Tuple Unpacking
Tuple unpacking (or sequence unpacking) allows you to assign the elements of a tuple to multiple variables.
coordinates = (10, 20)
x, y = coordinates
print(f"X: {x}, Y: {y}") # Output: X: 10, Y: 20
person_info = ("Alice", 30, "New York")
name, age, city = person_info
print(f"Name: {name}, Age: {age}, City: {city}") # Output: Name: Alice, Age: 30, City: New York
# Using asterisk (*) to catch remaining values
numbers = (1, 2, 3, 4, 5, 6)
first, *middle, last = numbers
print(f"First: {first}") # Output: First: 1
print(f"Middle: {middle}") # Output: Middle: [2, 3, 4, 5] (Note: middle is a list)
print(f"Last: {last}") # Output: Last: 6
Tuple Methods
Tuples have only two built-in methods due to their immutability:
my_tuple = (1, 5, 2, 8, 5, 3, 5)
# count(value): Returns the number of times a specified value occurs in a tuple
print(f"Count of 5: {my_tuple.count(5)}") # Output: Count of 5: 3
# index(value): Searches the tuple for a specified value and returns its position
print(f"Index of 8: {my_tuple.index(8)}") # Output: Index of 8: 3
# print(my_tuple.index(99)) # This would raise a ValueError if 99 is not found
When to Use Tuples vs. Lists?
Choosing between lists and tuples depends on your specific needs:
📋 Lists
[]
📦 Tuples
()
🏋️ Practice Exercise: Student Record System
Imagine you are building a simple student record system. Each student record should contain their name, age, and grade. Since these pieces of information for a single student are related and should ideally not change once recorded, use tuples to represent each student's data.
Create a list of student tuples and then write code to:
- Add a new student record.
- Display all student records.
- Find a student by name and display their details.
# You'll need a list to hold multiple student tuples.
# To "add" a student, you'll append a new tuple to the list.
# To find a student, iterate through the list of tuples.