xSKILLby Infirals
Register

Python for Beginners

0 of 24 notes read 0%

Reading progress is saved to your INFIRALS account. Sign in to keep this note marked as read.

Iterators and generators

More Python10 min readLesson 2 of 7

2.1 Iteration is a protocol

for does not know about lists specifically. It asks an object for an iterator with iter(), then calls next() until StopIteration is raised. Lists, dictionaries, files and range objects all follow this protocol, which is why one loop syntax works everywhere.

A generator function uses yield. Calling it returns a generator object that runs only as you request values. Local state stays alive between yields, which makes generators a natural way to describe a sequence without storing it.

python
def countdown(start):
    while start > 0:
        yield start
        start -= 1

for value in countdown(3):
    print(value)

Output

3
2
1

Use a generator when each value depends on the previous one, when the source is a file or network stream, or when a helper would otherwise build a big intermediate list. A generator can be consumed only once.

Interview questions

2 questions from this note. Open one to see the answer; no account needed.

  • 01What is the difference between a list and a generator?

    A list holds every value in memory and can be read repeatedly. A generator computes values on demand and is exhausted after one pass.

  • 02What does yield do?

    It pauses the function, hands one value to the caller, and resumes from the same line on the next request.