Tuples in Python
Tuples in Python
Section titled “Tuples in Python”Introduction
Section titled “Introduction”A tuple is an immutable, ordered sequence — like a list that can never be changed. This immutability makes tuples faster, hashable, and semantically meaningful.
Creating Tuples
Section titled “Creating Tuples”empty = ()point = (3, 4)person = ("Alice", 30, "Engineer")
# Parentheses optionalcoords = 10, 20
# Single element tuple NEEDS commasingle = (42,) # Tuplenot_tuple = (42) # Just integer 42!Packing & Unpacking
Section titled “Packing & Unpacking”point = 3, 4 # Packingx, y = point # Unpackingprint(x, y) # 3 4
# Extended unpackingfirst, *rest = (1, 2, 3, 4, 5)print(rest) # [2, 3, 4, 5] (rest is list!)
# Swapx, y = 10, 20x, y = y, xTuple Methods
Section titled “Tuple Methods”t = (3, 1, 4, 1, 5, 9, 2, 6, 5)
print(t.count(1)) # 2print(t.index(5)) # 4print(5 in t) # TrueNamed Tuples
Section titled “Named Tuples”from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])p = Point(3, 4)print(p.x) # 3 — clear!print(p.y) # 4print(p[0]) # 3 — still supports indexing
# From typing (Python 3.6+)from typing import NamedTuple
class Point3D(NamedTuple): x: float y: float z: float = 0.0Tuple vs List
Section titled “Tuple vs List”| Feature | Tuple | List |
|---|---|---|
| Mutability | Immutable | Mutable |
| Memory | Smaller (~33% less) | More |
| Hashable | Yes (dict key) | No |
| Methods | 2 (count, index) | 11+ |
| Creation | Faster (~5x) | Slower |
Why It Matters
Section titled “Why It Matters”Tuples are ideal for fixed data (coordinates, RGB colors, database records) and as dictionary keys.
Interview Questions
Section titled “Interview Questions”Q1: Why are tuples faster than lists?
A: Tuples are stored more compactly with no over-allocation. Constant tuples can be reused. Iteration is optimized in CPython.
Q2: Can a tuple contain mutable elements?
A: Yes! A tuple with a list inside can have that list modified: t = ([1,2], 3); t[0].append(4) — this works!
Practice Exercises
Section titled “Practice Exercises”- Create a named tuple for 2D coordinates and calculate distance.
- Demonstrate the difference between
==andiswith tuples. - Compare memory usage of a tuple vs list with the same data.