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.
What is a generator in Python?
A. A function that generates random numbers
B. A special type of list
C. A way to define classes
D. A function that yields values one at a time
How is a generator different from a regular function?
A. A generator uses the return keyword
B. A generator can yield multiple values
C. A generator uses the break statement
D. A generator uses the continue statement
What is an advantage of using generators for large datasets?
A. They use more memory
B. They are slower than loops
C. They are easier to implement
D. They use less memory
How do you define a generator function in Python?
A. Using the generator keyword
B. Using the def keyword and yield statement
C. Using the gen keyword
D. Using the function keyword

Join The Discussion