► Understanding Tuples
Tuples are immutable sequences in Python, similar to lists but cannot be modified after creation. They’re used to store related data that shouldn’t change, like coordinates or database records.
► Real-World Analogy
Think of tuples like a sealed envelope with documents:
» Once you seal the envelope (create tuple), you can’t change what’s inside
» You can read the contents but not modify them
» The envelope protects the data from accidental changes
» You can make copies but the original stays intact
» Perfect for storing fixed records like dates (year, month, day)
► Key Concepts
✓ Immutable: Cannot be changed after creation
✓ Ordered: Items maintain their position
✓ Indexed: Access items using position numbers
✓ Parentheses syntax: Created with ()
✓ Faster than lists: Due to immutability
■ Code Examples
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
# Creating tuples coordinates = (10, 20) person = ("Alice", 25, "Engineer") single = (42,) # Note the comma for single element empty = () print(coordinates) print(person[0]) # Tuple unpacking x, y = coordinates print(f"X: {x}, Y: {y}") name, age, job = person print(f"{name} is {age} years old") # Tuple operations print(f"Length: {len(person)}") print(f"Is 'Alice' in tuple? {'Alice' in person}") # Tuples are immutable try: coordinates[0] = 15 except TypeError as e: print(f"Error: Cannot modify tuple") # Using tuples as dictionary keys locations = {(0, 0): "Origin", (10, 20): "Point A"} print(locations[(0, 0)]) |
