Cross_Column

Monday, 19 January 2026

Generators and Iterators in Python




Generators and Iterators in Python

Iterators and Generators in Python are used to iterate over data efficiently. They help in handling large datasets by producing values one at a time instead of storing everything in memory.


What is an Iterator?

An iterator is an object that contains a countable number of values and can be traversed one by one.

An iterator must implement two methods:

  • __iter__()
  • __next__()

Iterator Example


my_list = [10, 20, 30]
iterator = iter(my_list)

print(next(iterator))
print(next(iterator))
print(next(iterator))


StopIteration Exception

When there are no more values, Python raises a StopIteration exception.


print(next(iterator))  # Raises StopIteration


Creating a Custom Iterator


class Count:
    def __init__(self, max):
        self.num = 1
        self.max = max

    def __iter__(self):
        return self

    def __next__(self):
        if self.num <= self.max:
            value = self.num
            self.num += 1
            return value
        else:
            raise StopIteration


counter = Count(3)

for i in counter:
    print(i)


What is a Generator?

A generator is a special type of iterator created using a function and the yield keyword.

Generators automatically handle __iter__() and __next__().


Generator Function Example


def my_generator():
    yield 1
    yield 2
    yield 3


gen = my_generator()

print(next(gen))
print(next(gen))
print(next(gen))


Generator with Loop


def count_up(max):
    num = 1
    while num <= max:
        yield num
        num += 1


for i in count_up(5):
    print(i)


Difference Between Iterator and Generator

Iterator Generator
Uses __iter__() and __next__() Uses yield keyword
More code required Less and cleaner code
Manual implementation Automatic implementation

Generator Expression

Generator expressions are similar to list comprehensions but use parentheses instead of square brackets.


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

for i in gen:
    print(i)


Memory Efficiency


# List comprehension
list_data = [x for x in range(1000000)]

# Generator expression
gen_data = (x for x in range(1000000))

Generators consume much less memory than lists.


Generators and Iterators in Automation Testing


def test_data():
    yield ("user1", "pass1")
    yield ("user2", "pass2")


for username, password in test_data():
    print(username, password)

Used in:

  • Reading large test data
  • API pagination handling
  • Log file processing

Best Practices

  • Use generators for large datasets
  • Prefer generators over lists when possible
  • Handle StopIteration properly

Common Interview Questions

  • What is an iterator?
  • What is a generator?
  • Difference between yield and return?
  • What is StopIteration?
  • Generator vs list comprehension?

Conclusion

Generators and iterators help write memory-efficient and scalable Python code. They are widely used in data processing, automation testing, and real-world applications.

👉 Learn more advanced Python concepts on way2testing.com

No comments:

Post a Comment

Few More

Multithreading and Multiprocessing in Python

Multithreading and Multiprocessing in Python Python provides powerful tools to perform multiple tasks simultaneously usi...