Python Tuples
Python Tuples
1. Introduction to Tuples
Definition
Creating Tuples
# Empty tuple
empty_tuple = ()
# Multiple elements
numbers = (1, 2, 3, 4, 5)
mixed_tuple = (1, "hello", 3.14, True)
# Tuple packing
coordinates = 3, 4 # Parentheses are optional
2. Accessing Tuples
Index-Based Access
coordinates = (4, 5, 6)
Slicing
numbers = (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
4. Tuple Unpacking
Basic Unpacking
# Simple unpacking
x, y, z = (1, 2, 3)
print(x) # Output: 1
print(y) # Output: 2
print(z) # Output: 3
# Swapping values
a, b = 10, 20
a, b = b, a # Easy swap using tuple packing and unpacking
Advanced Unpacking
# Using * to capture multiple elements
first, *middle, last = (1, 2, 3, 4, 5)
print(first) # Output: 1
print(middle) # Output: [2, 3, 4]
print(last) # Output: 5
Enumerated Loop
colors = ('red', 'green', 'blue')
for x, y in points:
print(f"X: {x}, Y: {y}")
6. Tuple Methods
Built-in Methods
numbers = (1, 2, 2, 3, 2, 4, 5)
Common Operations
# Concatenation
tuple1 = (1, 2, 3)
tuple2 = (4, 5, 6)
combined = tuple1 + tuple2 # (1, 2, 3, 4, 5, 6)
# Repetition
repeated = tuple1 * 2 # (1, 2, 3, 1, 2, 3)
# Membership testing
print(2 in tuple1) # True
print(5 in tuple1) # False
7. Nested Tuples
Creating and Accessing Nested Tuples
# Creating nested tuples
matrix = ((1, 2, 3), (4, 5, 6), (7, 8, 9))
# Accessing elements
print(matrix[0]) # (1, 2, 3)
print(matrix[0][1]) # 2
# Nested unpacking
(a, b, c), (d, e, f), (g, h, i) = matrix
8. Practical Exercises
Exercise 1: Basic Tuple Operations
# Create a tuple of months
months = ('Jan', 'Feb', 'Mar', 'Apr', 'May')
# Tasks:
# 1. Print the third month
# 2. Slice the first three months
# 3. Check if 'Jul' exists in the tuple
Exercise 2: Tuple Unpacking
# Tasks:
# 1. Unpack into variables
# 2. Print formatted string with all info
# Tasks:
# 1. Extract all x-coordinates
# 2. Calculate the perimeter
# 3. Print formatted coordinates