Slicing Lazy Generators: `itertools.islice`
Generators cannot be sliced with `gen[0:5]` because they have no index 🚫. Use `itertools.islice()` to slice lazy streams safely ✂️.
import itertools
def infinite_odds():
n = 1
while True:
yield n
n += 2
# Slice the first 3 elements of an infinite generator:
first_three = list(itertools.islice(infinite_odds(), 3))
print(first_three) # [1, 3, 5] ⚡
# 24. Slicing Lazy Generators: `itertools.islice` Generators cannot be sliced with `gen[0:5]` because they have no index 🚫. Use `itertools.islice()` to slice lazy streams safely ✂️: ```python import itertools def infinite_odds(): n = 1 while True: yield n n += 2 # Slice the first 3 elements of an infinite generator: first_three = list(itertools.islice(infinite_odds(), 3)) print(first_three) # [1, 3, 5] ⚡ ``` If you try to slice a 10GB streaming file with normal bracket indexing, Python explodes. `islice()` consumes only the requested window without loading the rest of the stream into memory. 🚀 --- ### Question Why does typing `gen[0:10]` on a generator object raise a `TypeError`? 💥 - [ ] a. Generators do not support indexing because values are produced on demand, not stored in RAM 🧠 - [ ] b. Python requires slicing generators with curly braces `{0:10}` - [ ] c. Because the compiler lost its scissors ✂️ - [ ] d. Generators are strictly read-only after 5:00 PM ⏰ --- ### Challenge Use `itertools.islice(range(100), 2, 5)` to grab 3 items starting at index 2. Convert to `list()` and print it. 🎯 <details> <summary>Solution</summary> ```python import itertools sliced = list(itertools.islice(range(100), 2, 5)) print(sliced) ``` </details>