Python Programming - Generators - Discussion

Discussion Forum : Generators - General Questions (Q.No. 39)
39.
How does the generator.__iter__() method differ from the iter() built-in function when applied to a generator?
They are equivalent in functionality
generator.__iter__() is not a valid method for generators
generator.__iter__() returns the generator itself, while iter() returns a new iterator
iter() is used for generators, and generator.__iter__() is used for other iterable objects
Answer: Option
Explanation:
generator.__iter__() returns the generator itself, treating the generator as its own iterator. iter() returns a new iterator object for the generator.
def my_generator():
    yield 1
    yield 2
    yield 3

# Using generator.__iter__()
gen_iter = my_generator().__iter__()
print(next(gen_iter))  # Output: 1

# Using iter()
iter_obj = iter(my_generator())
print(next(iter_obj))  # Output: 1
Discussion:
Be the first person to comment on this question !

Post your comments here:

Your comments will be displayed after verification.