Loading

Quipoin Menu

Learn • Practice • Grow

python / Iterators and Generators
tutorial

Iterators and Generators

Iterators are objects that allow you to traverse through a sequence. Generators are a simple way to create iterators using the `yield` keyword. They are memory‑efficient and useful for processing large datasets.

Iterators
An object is an iterator if it implements `__iter__()` and `__next__()`. The `iter()` function gets an iterator from a sequence, and `next()` gets the next value. Many built‑ins are iterable, but you can also create custom iterators.


numbers = [1, 2, 3]
it = iter(numbers)
print(next(it)) # 1
print(next(it)) # 2

class CountDown:
def __init__(self, start):
self.current = start
def __iter__(self):
return self
def __next__(self):
if self.current <= 0:
raise StopIteration
value = self.current
self.current -= 1
return value

for i in CountDown(3):
print(i) # 3,2,1

Generators
A generator is a function that uses `yield` to return values lazily. When called, it returns a generator iterator. It suspends state between yields.


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

for i in count_down(3):
print(i) # 3,2,1

# Generator expression (like list comprehension but lazy)
squares = (x*x for x in range(10))
print(next(squares)) # 0
Two Minute Drill
  • Iterators support `__iter__` and `__next__`; they produce values one at a time.
  • Generators use `yield` and are easier to write; they suspend state.
  • Generator expressions are like list comprehensions but lazy.
  • Both are memory‑efficient for large sequences.

Need more clarification?

Drop us an email at career@quipoinfotech.com