Skip to content
Omni Academy
Search courses and lessons
Search
Courses
Backend Development
9
Databases
1
Frontend Development
5
Data Science
5
All courses →
Playground
HTML & CSS
JavaScript
TypeScript
Python
PHP
Ruby
Light
Dark
Auto
Sign in
Get started
All
Backend Development
Databases
Frontend Development
Data Science
Playground
Blog
HTML
JS
TS
PY
PHP
RB
← Courses
📄
Generators and laziness
Run as I type
Reset
▶
Run
Ctrl
↵
PY
Python source code
# A generator produces values one at a time, so an endless sequence is # perfectly safe as long as something decides when to stop taking. from itertools import islice def fibonacci(): a, b = 0, 1 while True: yield a a, b = b, a + b print(list(islice(fibonacci(), 10))) # Nothing above computed more than ten numbers. This proves it: def counted(): n = 0 while True: n += 1 print(f" (produced {n})") yield n print("Took:", list(islice(counted(), 3))) # A generator expression is the same idea with lighter syntax. This one # describes a million squares and computes five. squares = (x * x for x in range(1_000_000)) print("First five squares:", list(islice(squares, 5)))
Input
one line per
input()
call
Output
Rendered by your browser