Generators

Creating iterators with yield

Interview Relevant: Very common in interviews

Generators

Functions that use yield to produce a sequence of values lazily.

Code Examples

python
1def fibonacci(n):
2    a, b = 0, 1
3    for _ in range(n):
4        yield a
5        a, b = b, a + b
6
7gen = fibonacci(5)
8print(list(gen))  # [0, 1, 1, 2, 3]

AI Tutor

Ask about the topic

Sign in Required

Please sign in to use the AI tutor

Sign In