⚡ Generators
Generators are a simple way of creating iterators. They use the `yield` statement.
Mastering this concept will significantly boost your Python data science skills!
💻 Code Example:
# 1. Basic generator function def countdown(n: int): """Counts down from n to 1 — one value at a time.""" while n > 0: yield n n -= 1 gen = countdown(5) print("First:", next(gen)) # 5 print("List:", list(gen)) # [4, 3, 2, 1] (generator exhausted after this) # 2. Infinite generator — produces endless sequence def pynfinity_ids(prefix="PYN"): """Infinite auto-incrementing ID generator.""" n = 1 while True: yield f"{prefix}-{n:06d}" n += 1 id_gen = pynfinity_ids() for _ in range(3): print(next(id_gen)) # PYN-000001, PYN-000002, PYN-000003 # 3. Generator pipeline — memory-efficient ETL def read_scores(data): for record in data: yield record def filter_passing(records, threshold=60): for r in records: if r["score"] >= threshold: yield r def enrich(records, platform="pynfinity"): for r in records: r["badge"] = "✅" if r["score"] >= 90 else "📘" r["platform"] = platform yield r raw_data = [ {"name": "santoshtvk", "score": 95}, {"name": "dhruv", "score": 88}, {"name": "tvk", "score": 45}, {"name": "alice", "score": 72}, ] # Chain pipelines — each step is lazy pipeline = enrich(filter_passing(read_scores(raw_data))) for record in pipeline: print(record) # 4. yield from — delegate to sub-generator def all_courses(): yield from ["Python", "AI", "DevOps"] # Flatten nested yield yield from ["Testing", "Docker"] print("\nAll courses:", list(all_courses())) # 5. Generator with send() — bidirectional communication def xp_accumulator(): total = 0 while True: action = yield total # Pauses, returns total, awaits send() if action is None: break XP = {"login": 10, "challenge": 30, "pebble": 100} total += XP.get(action, 0) acc = xp_accumulator() next(acc) # Prime the generator acc.send("login") acc.send("pebble") final = acc.send("challenge") print("\nTotal XP via send():", final) # 140
Keep exploring and happy coding! 💻