Infinite Iterators: `itertools.count` and `itertools.cycle`
`itertools.count(start, step)` produces numbers infinitely βΎοΈ. `itertools.cycle(seq)` loops over a sequence forever like a broken record π.
import itertools
# Infinite sequence:
counter = itertools.count(start=10, step=5)
print(next(counter)) # 10
print(next(counter)) # 15
# Repeating carousel:
turn = itertools.cycle(["RED", "GREEN"])
print(next(turn), next(turn), next(turn)) # RED GREEN RED π¦
# 22. Infinite Iterators: `itertools.count` and `itertools.cycle` `itertools.count(start, step)` produces numbers infinitely βΎοΈ. `itertools.cycle(seq)` loops over a sequence forever like a broken record π: ```python import itertools # Infinite sequence: counter = itertools.count(start=10, step=5) print(next(counter)) # 10 print(next(counter)) # 15 # Repeating carousel: turn = itertools.cycle(["RED", "GREEN"]) print(next(turn), next(turn), next(turn)) # RED GREEN RED π¦ ``` Infinite iterators take zero memory because they calculate values lazily on the fly. Just make sure your loops have termination guards, or your terminal will melt! π¨ --- ### Question What happens if you run `for x in itertools.count():` without a `break`? π₯ - [ ] a. The loop runs infinitely until you manually kill the process with Ctrl+C π - [ ] b. Python stops automatically after 1,000,000 counts to conserve electricity β‘ - [ ] c. The CPU sets a new world record and gives you an achievement badge π - [ ] d. It rolls over into negative numbers and deletes your home directory π± --- ### Challenge Use `itertools.cycle(["A", "B"])` to grab 3 items in a row with `next()`. Print the 3rd item. π― <details> <summary>Solution</summary> ```python import itertools c = itertools.cycle(["A", "B"]) next(c) next(c) print(next(c)) ``` </details>