# starred unpacking
a, *rest = (1, 2, 3, 4) # rest = [2, 3, 4]
first, *mid, last = range(5)
# set ops (O(1) membership)
{1,2,3} & {2,3,4} # {2,3} intersection
{1,2,3} | {2,3,4} # {1,2,3,4} union
{1,2,3} - {2,3,4} # {1} difference
s.discard(x) # no error if missing (s.remove raises KeyError)
# dict
d.get("key", default)
for k, v in d.items(): ...
sorted(d.items(), key=lambda i: i[1]) # sort by value
d1 | d2 # merge (3.9+)
from collections import Counter, defaultdict, deque, namedtuple
from typing import NamedTuple
Counter("abracadabra").most_common(2) # [("a",5),("b",2)]
Counter("abc")["z"] # 0 — no KeyError
graph = defaultdict(list)
graph["A"].append("B") # no KeyError on first access
q = deque(maxlen=3) # auto-evicts oldest when full
q.appendleft(x) # O(1) — list.insert(0,x) is O(n)
# namedtuple — immutable, tuple-compatible, named fields
Point = namedtuple("Point", ["x", "y"])
p = Point(1, 2); p.x # 1
class Coord(NamedTuple): # typed + default support
x: float; y: float = 0.0
# heapq — min-heap; always gives smallest first
import heapq
h = [3, 1, 4]; heapq.heapify(h) # O(n) in place
heapq.heappush(h, 2); heapq.heappop(h)
heapq.nsmallest(2, h) # top-k without full sort
heapq.heappush(h, (-score, item)) # max-heap: negate the key
# Enum — named constants, identity comparison
from enum import Enum, auto
class Status(Enum):
PENDING = auto(); DONE = auto()
Status.PENDING.name # "PENDING"
Status.PENDING.value # 1
Status["PENDING"] # lookup by name
for i, v in enumerate(items, start=1): ...
for a, b in zip(xs, ys): ... # stops at shortest
all(x > 0 for x in vals) # short-circuits on False
any(x > 0 for x in vals) # short-circuits on True