Python Tutorial
Python Access Set Items
Sets are unordered and unindexed. You cannot use [0]. Loop or use in instead.
Loop and Membership
for and in are the ways to look at set items.
thisset = {"apple", "banana", "cherry"}
for x in thisset:
print(x)
print("banana" in thisset)
print("mango" not in thisset)📘 Real-World Deep Dive
The right form of set access — <code>in</code> for membership, O(1); <code>for x in s</code> for iteration, with no index — is the cheapest lookup in the language.
Real-Life Scenario
A fast allow-list / deny-list authorisation check on every request — two <code>set</code>s, no DB round-trip.
Real-Life Example
from dataclasses import dataclass
@dataclass(frozen=True)
class Auth:
allow_paths: frozenset[str]
deny_paths: frozenset[str]
deny_users: frozenset[str]
POLICY = Auth(
allow_paths=frozenset({"/api/users", "/api/orders", "/health"}),
deny_paths =frozenset({"/api/admin", "/internal"}),
deny_users =frozenset({"attacker@example.com"}),
)
def authorise(request_user: str, path: str) -> bool:
if request_user in POLICY.deny_users: return False
if path in POLICY.deny_paths: return False
if path in POLICY.allow_paths: return True
return False # default-deny
calls = [
("ada@example.com", "/api/users"),
("ada@example.com", "/api/admin"),
("attacker@example.com", "/api/users"),
("bo@example.com", "/unknown"),
]
for user, path in calls:
print(f"{user:<22} {path:<14} -> {authorise(user, path)}")Expected Output
ada@example.com /api/users -> True
ada@example.com /api/admin -> False
attacker@example.com /api/users -> False
bo@example.com /unknown -> FalseCommon mistakes
- Membership
inon alistis O(n) — always membership-test sets and dicts when possible. - Iteration order in a set is unspecified — sort explicitly when a stable order matters.
frozensetis hashable so it works as a dict key or another set member;setdoesn't.
🚀 Performance & Best Practices
- Sets use a hash table with amortised O(1) lookups;
inis the cheapest test you can run. - For 100 k-items lookups, sets beat lists by ~1000×.
- Use
set(a) & set(b)for intersection — don't hand-roll it.
🧪 Try It Yourself
- Refactor
POLICYto read from a JSON file at startup. - Add a metrics counter for hits/misses on each check.
- Implement an audit-log line that records the rule that denied each request.