What is the role of the __iter__() and __next__() methods in iterators?
A. They define the class constructor
B. They define the class destructor
C. They define iteration behavior
D. They define the yield keyword
Answer: Option C
Solution (By Examveda Team)
The correct answer is Option C: They define iteration behavior.The iter() and next() methods in iterators are used to define the iteration behavior of an object.
iter() method returns the iterator object itself and is called when the iterator is initialized. It sets up the iterator for iteration.
next() method returns the next item in the sequence and is called each time the next item is requested during iteration. It raises a StopIteration exception when there are no more items to return.
These methods together define the iterator protocol, allowing objects to be iterated over using a for loop or by calling the next() function.
Join The Discussion