- What tuples are and when to use them over lists
- Packing and unpacking
- Named tuples
| Concept | JavaScript | Python |
|---|---|---|
| Immutable array | Object.freeze([1,2,3]) |
(1, 2, 3) |
| Destructuring | const [x, y] = [1, 2] |
x, y = (1, 2) |
| Multiple return | return array | return tuple |
# Tuples use parentheses (or just commas)
point = (10, 20)
rgb = (255, 128, 0)
single = (42,) # trailing comma needed for single-item tuple!
empty = ()
# Parentheses are optional
coords = 10, 20 # also a tuplelst = [1, 2, 3] # mutable β can change
tup = (1, 2, 3) # immutable β cannot change
lst[0] = 99 # β
works
tup[0] = 99 # β TypeError: 'tuple' object does not support item assignmentUse tuples when:
- Data should not change (coordinates, RGB, DB rows)
- You want to return multiple values from a function
- You need a hashable key in a dict
# Basic unpacking
x, y = (10, 20)
print(x, y) # 10 20
# With star (*) for rest
first, *rest = (1, 2, 3, 4, 5)
print(first) # 1
print(rest) # [2, 3, 4, 5]
*start, last = (1, 2, 3, 4, 5)
print(last) # 5
# Swap variables (Python classic)
a, b = 1, 2
a, b = b, a # swap!
# Function returning multiple values
def min_max(lst):
return min(lst), max(lst) # returns a tuple
lo, hi = min_max([3, 1, 7, 2])
print(lo, hi) # 1 7Like a lightweight class or JS object β gives names to positions.
from collections import namedtuple
Point = namedtuple("Point", ["x", "y"])
Color = namedtuple("Color", ["red", "green", "blue"])
p = Point(10, 20)
print(p.x, p.y) # 10 20
print(p[0]) # 10 β index still works
c = Color(255, 128, 0)
print(c.red) # 255| Mistake | Wrong | Right |
|---|---|---|
| Single item tuple | (42) β this is just 42! |
(42,) β trailing comma |
| Mutating tuple | t[0] = 5 |
Use a list if you need mutability |
π 08 β Dictionaries