Page7/20
Lists & Tuples Β· Page 2 of 2
Tuples & When to Use Them
Tuples β Immutable Sequences
A tuple is like a list but immutable β once created, it cannot be changed. Use tuples for data that should not be modified.
coordinates = (40.7128, -74.0060) # New York lat/lon
rgb_red = (255, 0, 0)
List vs Tuple β When to Use Which?
| List | Tuple | |
|---|---|---|
| Syntax | [1, 2, 3] | (1, 2, 3) |
| Mutable | β Yes | β No |
| Use for | Changing data | Fixed records |
| Performance | Slightly slower | Faster |
| Hashable | β No | β Yes |
Tuple Unpacking
One of Python's most elegant features:
point = (10, 20)
x, y = point # x=10, y=20
# Swap variables without temp
a, b = 5, 10
a, b = b, a # a=10, b=5
Named Tuples
For readability, use collections.namedtuple:
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
p = Point(10, 20)
print(p.x, p.y) # 10 20
main.py
Loading...
OUTPUT
βΆClick "Run Code" to executeβ¦