Back
+15 XP
Concept

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 🚦

# 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>

Checkpoint

What happens if you run `for x in itertools.count():` without a `break`? πŸ’₯

Practice

Use `itertools.cycle(["A", "B"])` to grab 3 items in a row with `next()`. Print the 3rd item. 🎯

Terminal
01
Tap code blocks below to assemble
Available Blocks