Iterators and Generators

📘 Python 👁 65 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

Iterators and Generators in Python

Python provides iterators and generators to efficiently handle sequences and large data streams. They allow lazy evaluation, meaning values are computed only when needed, saving memory.


1. Iterators

  • An iterator is an object that can be iterated over (looped through).

  • It implements the methods __iter__() and __next__().

Creating an iterator:

my_list = [1, 2, 3] it = iter(my_list) # convert list to iterator print(next(it)) # 1 print(next(it)) # 2 print(next(it)) # 3 # print(next(it)) # StopIteration error

Using iterator in a loop:

for value in my_list: print(value)

Custom iterator class:

class MyNumbers: def __init__(self, start, end): self.current = start self.end = end def __iter__(self): return self def __next__(self): if self.current > self.end: raise StopIteration else: self.current += 1 return self.current - 1 nums = MyNumbers(1, 5) for n in nums: print(n)

2. Generators

  • A generator is a function that yields values one by one using the yield keyword.

  • They are memory-efficient because they generate values on demand.

Basic generator example:

def my_generator(): yield 1 yield 2 yield 3 gen = my_generator() print(next(gen)) # 1 print(next(gen)) # 2 print(next(gen)) # 3

Using generators in a loop:

for value in my_generator(): print(value)

Generator with a sequence (lazy evaluation):

def squares(n): for i in range(n): yield i * i for sq in squares(5): print(sq) # 0 1 4 9 16

Generator expressions (like list comprehensions but lazy):

gen_exp = (x*x for x in range(5)) for value in gen_exp: print(value)

3. Advantages of Iterators and Generators

  • Memory efficient: No need to store the entire sequence.

  • Lazy evaluation: Values are computed only when required.

  • Infinite sequences: Can generate sequences without storing them.

  • Simpler code: Cleaner syntax for iteration using for loops.


4. Practical Example: Fibonacci Sequence Generator

def fibonacci(n): a, b = 0, 1 for _ in range(n): yield a a, b = b, a + b for num in fibonacci(10): print(num) # 0 1 1 2 3 5 8 13 21 34

Key Points

  • iter() converts iterable objects into iterators.

  • next() fetches the next value from an iterator.

  • yield in a generator function pauses the function and returns a value.

  • Generators are ideal for large data streams or infinite sequences.

  • Both iterators and generators support for loops directly.


🔒 Some advanced sections are available for Registered Members
Register Now

Share this Post


← Back to Tutorials

Popular Competitive Exam Quizzes