Generators & Iterators Flashcards

(10 cards)

1
Q

What is an Iterator?

A

An object that produces values one at a time using __next__() and stops with StopIteration.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

__iter__ vs __next__

A

__iter__() → returns the iterator object

__next__() → returns next value or raises StopIteration

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

How does a for loop work internally?

A

it = iter(obj)
next(it) # repeatedly until StopIteration

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is a generator?

A

A function that yields values one by one using yield instead of returning all at once.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What does yield do?

A

Returns a value, pauses the function, and resumes from the same point on next call.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Generator vs list difference?

A

List → stores all values in memory

Generator → produces values lazily (on demand)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Generator Expression

A

A compact generator using () instead of []

(x*x for x in range(5))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Why are generators useful?

A

Memory efficiency, handling large data, lazy evaluation.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

How do you read large CSV without loading into RAM?

A

Use a generator to read line by line:

def read_csv(file):
with open(file) as f:
for line in f:
yield line.strip().split(‘,’)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the main idea behind generators?

A

Process data one at a time instead of all at once.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly