Generators Questions and Answers
Python Programming - Generators Questions with Answers focus on efficient data iteration using the `yield` keyword. These Python Generators Questions are helpful for TCS, Infosys, and Capgemini exams to test knowledge of memory-efficient programming techniques
Generators
Showing 10 of
25 questions
11. What is the difference between return and yield?
- return ends function, yield pauses it
- yield ends function, return pauses it
- Both work the same way
- return is for generators, yield for normal functions
12. Can generators be used with infinite sequences?
- Yes
- No
- Only with special imports
- Only in Python 2
13. How do you create a generator that yields numbers from 0 to n?
- def gen(n): for i in range(n): yield i
- def gen(n): return range(n)
- def gen(n): yield range(n)
- def gen(n): return [i for i in range(n)]
14. What is generator comprehension?
- Creating generators with concise syntax
- Reading generator documentation
- Optimizing generator performance
- Debugging generator functions
15. Can you send values back into a generator?
- Yes, using send() method
- No, generators are read-only
- Only in Python 2
- Only with special decorators
16. What does the close() method do on a generator?
- Raises GeneratorExit in generator
- Deletes the generator from memory
- Resets the generator to start
- Continues execution till end
17. What is the purpose of yield from in Python?
- Delegate to another generator
- Yield from a specific index
- Create a new generator
- Yield all values at once
18. Can generators be pickled in Python?
- No
- Yes
- Only in Python 2
- Only with simple generators
19. What is the state of a generator between yield calls?
- Suspended
- Running
- Terminated
- Reset
20. How are generators different from iterator objects?
- Generators use yield, iterators use __next__
- Iterators are faster
- Generators are not iterators
- No difference