Topic 05 / 15
Lists & Tuples
Lists — Ordered & Mutable
stack = ["python", "django", "react"]
stack[0] # 'python' — zero-indexed
stack[-1] # 'react' — negative = from the end
len(stack) # 3
"django" in stack # True — membership testSlicing — Read Any Sub-Sequence
The pattern is list[start:stop:step] — start is included, stop is not:
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
nums[2:5] # [2, 3, 4]
nums[:3] # [0, 1, 2] — from the beginning
nums[7:] # [7, 8, 9] — to the end
nums[::2] # [0, 2, 4, 6, 8] — every 2nd
nums[::-1] # reversed copy
nums[:] # full shallow copyMutating Lists
stack.append("fastapi") # add to the end — O(1)
stack.insert(0, "html") # add at index — O(n)
stack.extend(["sql", "git"]) # append many
stack.remove("html") # remove first matching value
last = stack.pop() # remove & return the last item
stack[1] = "django 5" # replace by index
del stack[0] # delete by indexSorting
scores = [82, 41, 99, 67]
sorted(scores) # NEW sorted list — original untouched
scores.sort() # sorts IN PLACE, returns None
scores.sort(reverse=True)
# sort by a key function
users = [("ravi", 82), ("asha", 99), ("dev", 41)]
users.sort(key=lambda u: u[1], reverse=True)
# [('asha', 99), ('ravi', 82), ('dev', 41)]Lists Are References — the #1 Beginner Bug
a = [1, 2, 3]
b = a # b is the SAME list, not a copy
b.append(4)
print(a) # [1, 2, 3, 4] — surprise!
c = a.copy() # actual copy (or a[:], or list(a))
c.append(5)
print(a) # unchangedTuples — Ordered & Immutable
A tuple is a frozen sequence. Use it for fixed-shape data — coordinates, RGB values, database rows:
point = (28.6139, 77.2090)
point[0] # 28.6139
point[0] = 1.0 # TypeError — tuples can't changeImmutability is a feature: tuples can be dict keys and set members, and they signal “this data has a fixed structure”. Unpacking makes them ergonomic:
lat, lng = point
for name, score in [("ravi", 82), ("asha", 99)]:
print(f"{name}: {score}")List or Tuple?
- List — homogeneous items, length varies: a list of users, a queue of jobs.
- Tuple — heterogeneous fields, fixed shape:
(name, score),(x, y).