Lecture 2: Tuples in Python

1. Tuple Initialization

Tuples are ordered, immutable collections that can store elements of different data types.

# Empty tuple empty_tuple = () # Single element tuple (note the trailing comma) single = (1,) # Multiple elements numbers = (1, 2, 3, 4, 5) mixed = (1, "hello", 3.14, True) # Without parentheses (tuple packing) colors = 'red', 'green', 'blue' # Using tuple() constructor chars = tuple("Python") # ('P', 'y', 't', 'h', 'o', 'n')

2. Tuple Methods

Tuples have only two built-in methods since they are immutable.

Method Description Example
count(x) Returns the number of times x appears in the tuple nums = (1, 2, 2, 3); nums.count(2) → 2
index(x) Returns the index of the first occurrence of x nums.index(3) → 3

3. Tuple Operations

Common operations on tuples.

# Concatenation tuple1 = (1, 2, 3) tuple2 = (4, 5, 6) combined = tuple1 + tuple2 # (1, 2, 3, 4, 5, 6) # Repetition repeated = (0,) * 5 # (0, 0, 0, 0, 0) # Membership exists = 3 in tuple1 # True # Length length = len(tuple1) # 3 # Indexing and Slicing (similar to lists) numbers = (10, 20, 30, 40, 50) first = numbers[0] # 10 last = numbers[-1] # 50 subset = numbers[1:4] # (20, 30, 40)

4. Nesting in Tuples

Tuples can contain other tuples, creating nested structures.

# Nested tuples coordinates = ((1, 2), (3, 4), (5, 6)) # Accessing nested elements x, y = coordinates[0] # x=1, y=2 # Mixed nesting data = (1, [2, 3], (4, 5), {"name": "John"}) # Tuple unpacking point = (3, 4) x, y = point # x=3, y=4 # Swapping variables using tuples a, b = 5, 10 a, b = b, a # a=10, b=5

5. List vs Tuple

Key differences between lists and tuples.

Feature List Tuple
Mutability Mutable (can be changed after creation) Immutable (cannot be changed after creation)
Syntax Uses square brackets [] Uses parentheses ()
Performance Slower for iteration Faster for iteration
Memory Consumes more memory Consumes less memory
Methods Many methods to modify the list Only count() and index()
Use Case For collections of similar items that need to change For heterogeneous data that shouldn't change
When to use tuples:
  • For data that shouldn't change (e.g., days of the week, months)
  • As dictionary keys (lists can't be used as dictionary keys)
  • For function arguments and return values when immutability is desired
  • When you need to ensure data integrity
# Dictionary with tuple keys location = {} point1 = (35.6895, 139.6917) # Tokyo location[point1] = "Tokyo" # Function returning multiple values (as a tuple) def get_dimensions(): return 1920, 1080 # Returns a tuple width, height = get_dimensions()