Skip to content

Latest commit

Β 

History

History
113 lines (78 loc) Β· 2.26 KB

File metadata and controls

113 lines (78 loc) Β· 2.26 KB

🐍 07 – Tuples

🎯 What You'll Learn

  • What tuples are and when to use them over lists
  • Packing and unpacking
  • Named tuples

πŸ“Œ JS vs Python β€” Side by Side

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

πŸ’‘ Creating Tuples

# 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 tuple

πŸ’‘ Tuple vs List

lst   = [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 assignment

Use 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

πŸ’‘ Unpacking

# 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 7

πŸ’‘ Named Tuples

Like 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

⚠️ Common Mistakes

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

πŸ”— Next Lesson

πŸ‘‰ 08 – Dictionaries