Examveda

How do you manually create an iterator in Python?

A. Using a generator function

B. Using a list comprehension

C. Using a for loop

D. Using a class with __next__() method

Answer: Option D

Solution (By Examveda Team)

The correct answer is Option D: Using a class with next() method.
To manually create an iterator in Python, you can define a class that implements the iterator protocol by including the iter() and next() methods. The iter() method returns the iterator object itself, and the next() method returns the next item in the sequence or raises a StopIteration exception when there are no more items to return. By using this approach, you have full control over the iteration behavior and can define custom logic for generating the sequence of values.

This Question Belongs to Python Program >> Generators And Iterators

Join The Discussion

Related Questions on Generators and Iterators