Tuples
Immutable lists — for storing fixed data
What is a Tuple?
A tuple is an immutable sequence in Python, similar to a list but cannot be modified after creation.
List vs Tuple
| Feature | List | Tuple |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutability | Mutable | Immutable |
| Speed | Slower | Faster |
| Usage | Dynamic data | Fixed data |
When to use tuples?
- Data should not be modified (e.g., coordinates, dates)
- As dictionary keys (lists cannot)
- Functions returning multiple values
Creating Tuples
1. Basic Creation
python
# Empty tuple
empty_tuple = ()
# Single element (note the comma!)
single = (5,) # ✅ This is a tuple
not_tuple = (5) # ❌ This is just the number 5
# Multiple elements
coordinates = (10, 20)
student_info = ("Alice", 25, "Economics")
# Without parentheses also works (but not recommended)
point = 10, 20
print(type(point)) # <class 'tuple'>2. Converting from List
python
ages_list = [25, 30, 35]
ages_tuple = tuple(ages_list)
print(ages_tuple) # (25, 30, 35)Accessing Tuple Elements
Indexing and Slicing (same as lists)
python
student = ("Alice", 25, "Economics", 3.85)
# Index access
print(student[0]) # Alice
print(student[-1]) # 3.85
# Slicing
print(student[1:3]) # (25, 'Economics')
print(student[:2]) # ('Alice', 25)Tuple Unpacking
python
# Basic unpacking
point = (10, 20)
x, y = point
print(f"x={x}, y={y}") # x=10, y=20
# Multiple variable unpacking
student = ("Alice", 25, "Economics")
name, age, major = student
print(name, age, major) # Alice 25 Economics
# Partial unpacking (using *)
scores = (85, 90, 78, 92, 88)
first, second, *rest = scores
print(first) # 85
print(second) # 90
print(rest) # [78, 92, 88] (Note: rest is a list!)Social Science Application:
python
# Survey data: (ID, gender, age, income)
respondent = (1001, "Female", 30, 75000)
# Unpack
resp_id, gender, age, income = respondent
print(f"Respondent {resp_id}: {gender}, {age} years old, income ${income:,}")Tuple Immutability
python
student = ("Alice", 25, "Economics")
# ❌ Cannot modify
student[1] = 26 # TypeError: 'tuple' object does not support item assignment
# ❌ Cannot append
student.append("GPA") # AttributeError: 'tuple' object has no attribute 'append'
# ❌ Cannot delete
del student[0] # TypeError
# ✅ Can replace entire tuple
student = ("Bob", 28, "Sociology")Why immutability?
- Prevent accidental modification of important data
- Can be used as dictionary keys
- Better performance
Tuple Operations
1. Basic Operations
python
numbers = (1, 2, 3, 4, 5, 2, 3)
# Length
print(len(numbers)) # 7
# Max/min/sum
print(max(numbers)) # 5
print(min(numbers)) # 1
print(sum(numbers)) # 20
# Count
print(numbers.count(2)) # 2
# Find index
print(numbers.index(3)) # 2 (first occurrence)
# Check existence
print(2 in numbers) # True2. Concatenation and Repetition
python
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
# Concatenation
combined = tuple1 + tuple2
print(combined) # (1, 2, 3, 4, 5, 6)
# Repetition
repeated = tuple1 * 3
print(repeated) # (1, 2, 3, 1, 2, 3, 1, 2, 3)🔬 Real-World Cases
Case 1: Geographic Coordinates
python
# City coordinates (longitude, latitude)
cities = {
"Beijing": (39.9042, 116.4074),
"Shanghai": (31.2304, 121.4737),
"Guangzhou": (23.1291, 113.2644)
}
# Calculate distance between Beijing and Shanghai (simplified)
import math
def calculate_distance(coord1, coord2):
lat1, lon1 = coord1
lat2, lon2 = coord2
# Simplified distance calculation
distance = math.sqrt((lat2 - lat1)**2 + (lon2 - lon1)**2)
return distance * 111 # Convert to km (rough)
beijing = cities["Beijing"]
shanghai = cities["Shanghai"]
dist = calculate_distance(beijing, shanghai)
print(f"Distance from Beijing to Shanghai: {dist:.0f} km")Case 2: Survey Metadata
python
# Survey basic info (should not be modified)
survey_metadata = (
"China Household Income Survey", # Survey name
"2024-01-01", # Start date
"2024-12-31", # End date
1000, # Target sample size
"Chinese" # Language
)
# Unpack
name, start_date, end_date, target_n, language = survey_metadata
print(f"=== Survey Information ===")
print(f"Name: {name}")
print(f"Period: {start_date} to {end_date}")
print(f"Target sample: {target_n}")
print(f"Language: {language}")Case 3: Function Returns Multiple Values
python
def calculate_statistics(data):
"""Calculate descriptive statistics, return tuple"""
n = len(data)
mean = sum(data) / n
sorted_data = sorted(data)
median = sorted_data[n//2]
minimum = min(data)
maximum = max(data)
return (n, mean, median, minimum, maximum)
# Usage
scores = [85, 92, 78, 90, 88, 76, 95, 82]
n, mean, median, min_val, max_val = calculate_statistics(scores)
print(f"Sample size: {n}")
print(f"Mean: {mean:.2f}")
print(f"Median: {median}")
print(f"Min: {min_val}")
print(f"Max: {max_val}")🔄 Converting Between Tuples and Lists
python
# List to tuple
ages_list = [25, 30, 35, 40]
ages_tuple = tuple(ages_list)
print(ages_tuple) # (25, 30, 35, 40)
# Tuple to list
ages_tuple = (25, 30, 35, 40)
ages_list = list(ages_tuple)
print(ages_list) # [25, 30, 35, 40]Practical scenario: When you need to modify a tuple
python
# Original tuple
student = ("Alice", 25, "Economics")
# Convert to list to modify
student_list = list(student)
student_list[1] = 26 # Modify age
student = tuple(student_list) # Convert back to tuple
print(student) # ('Alice', 26, 'Economics')🚀 Advanced: Named Tuples (namedtuple)
Problem with regular tuples: Can only access by index, not intuitive.
python
from collections import namedtuple
# Define named tuple
Student = namedtuple('Student', ['name', 'age', 'major', 'gpa'])
# Create instance
alice = Student(name="Alice", age=25, major="Economics", gpa=3.85)
# Access (two ways)
print(alice.name) # Alice (more intuitive)
print(alice[0]) # Alice (can also use index)
print(alice.gpa) # 3.85
print(alice[-1]) # 3.85
# Still a tuple, immutable
# alice.age = 26 # ❌ AttributeErrorSocial Science Application:
python
from collections import namedtuple
# Define survey response structure
Response = namedtuple('Response', [
'respondent_id',
'age',
'gender',
'income',
'education',
'satisfaction'
])
# Create response
resp1 = Response(
respondent_id=1001,
age=30,
gender="Female",
income=75000,
education="Bachelor's",
satisfaction=4
)
# Intuitive access
print(f"Respondent {resp1.respondent_id}:")
print(f" Age: {resp1.age}")
print(f" Income: ${resp1.income:,}")
print(f" Satisfaction: {resp1.satisfaction}/5")🤔 When to Use List vs Tuple?
| Scenario | Use List | Use Tuple |
|---|---|---|
| Collect respondent ages | ✅ ages = [25, 30, ...] | ❌ |
| Geographic coordinates | ❌ | ✅ point = (39.9, 116.4) |
| Survey metadata | ❌ | ✅ metadata = ("Survey", "2024") |
| Dynamically add data | ✅ data.append(x) | ❌ |
| Function returns multiple values | ❌ | ✅ return (mean, std, n) |
| As dictionary key | ❌ | ✅ {(x, y): value} |
Rule of thumb:
- Data will change → use list
- Data won't change → use tuple
⚠️ Common Errors
Error 1: Forgetting comma for single-element tuple
python
# ❌ Not a tuple
single = (5)
print(type(single)) # <class 'int'>
# ✅ Is a tuple
single = (5,)
print(type(single)) # <class 'tuple'>Error 2: Trying to modify tuple
python
coords = (10, 20)
coords[0] = 15 # ❌ TypeError: 'tuple' object does not support item assignmentError 3: Confusing tuple with list
python
# Tuples don't have append method
numbers = (1, 2, 3)
numbers.append(4) # ❌ AttributeError
# Should use list
numbers = [1, 2, 3]
numbers.append(4) # ✅💪 Practice Problems
Exercise 1: RGB Colors
python
# Define several colors (RGB tuples)
red = (255, 0, 0)
green = (0, 255, 0)
blue = (0, 0, 255)
# Tasks:
# 1. Create a function that takes RGB tuple, returns color name
# 2. Calculate "distance" between red and green (Euclidean distance)Exercise 2: Student Records
python
# Use named tuples to create student record system
# Fields: id, name, age, major, gpa
# Create 3 students, calculate average GPAExercise 3: Function Returns Multiple Values
python
# Write function to calculate income quartiles
incomes = [45000, 50000, 60000, 75000, 80000, 95000, 120000, 150000]
# Function returns (Q1, Q2, Q3) as tuple
# Hint: Sort and take 25%, 50%, 75% positions📚 Next Steps
In the next section, we'll learn about Dictionaries, one of Python's most powerful data structures, similar to R's named list.
Keep moving forward!