Exercise: Python

Questions for: Generators

How does the generator.__iter__() method differ from the iter() built-in function when applied to a generator?
A:
They are equivalent in functionality
B:
generator.__iter__() is not a valid method for generators
C:
generator.__iter__() returns the generator itself, while iter() returns a new iterator
D:
iter() is used for generators, and generator.__iter__() is used for other iterable objects
Answer: C
generator.__iter__() returns the generator itself, treating the generator as its own iterator. iter() returns a new iterator object for the generator.
What is the purpose of the itertools.groupby() function when used with generators?
A:
It groups consecutive equal elements from the generator
B:
It interleaves values from different generators
C:
It stops the generator after one iteration
D:
It creates pairs of values from the generators
Answer: A
itertools.groupby() groups consecutive equal elements from the generator based on a key function.
How can you implement a generator that produces a sequence of prime numbers?
A:
Using a loop with a yield statement and a prime-checking function
B:
By calling a recursive function with yield
C:
Using a list comprehension with yield
D:
By using the itertools.cycle() function
Answer: A
A generator for a sequence of prime numbers can be implemented using a loop with a yield statement and a function to check for prime numbers.
What is the purpose of the generator.__iter__() method?
A:
It returns the iterator object associated with the generator
B:
It initializes the generator
C:
It returns the generator itself
D:
It is not a valid method for generators
Answer: C
generator.__iter__() returns the generator itself. Generators are their own iterators in Python.
What does the generator.throw(ExceptionType, value) method do?
A:
It raises a custom exception inside the generator
B:
It raises a StopIteration exception
C:
It initializes the generator with the provided value
D:
It has no effect on the generator
Answer: A
generator.throw(ExceptionType, value) raises a custom exception of type ExceptionType with the specified value inside the generator.
Ad Slot (Above Pagination)
Quiz