Python Generators

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

Python: Generators

Generators in Python are a powerful mechanism for creating iterators. They allow you
to iterate over a sequence of data without needing to store the entire sequence in
memory at once. This can be particularly useful when dealing with large datasets or
infinite sequences.

Here's a detailed explanation of generators in Python:

What is a Generator?

A generator in Python is a special type of iterator that can be iterated over using a for
loop like any other iterable object such as lists or tuples. However, unlike lists, which
store all the elements in memory, generators produce elements on-the-fly as they are
requested, making them memory efficient.

Generator Functions

Generators are created using generator functions, which are defined using the def
keyword followed by a function name and a set of parentheses. However, unlike
regular functions, generator functions contain one or more yield statements, which
temporarily suspend the function’s execution, saving its state so it can resume where
it left off when called again.

python
Copy code
def my_generator():
yield 1
yield 2
yield 3

When a generator function is called, it returns a generator object, which is an iterator.


The yield keyword is what makes a function a generator. Each time the yield
statement is encountered, the function's state is saved, and the value is yielded to the
caller.

Using Generators

Generators are typically used in conjunction with loops to iterate over their elements.
This is because generators produce values lazily, i.e., they produce values only when
requested.

python
Copy code
gen = my_generator()
for value in gen:
print(value)

This will print:

Copy code
1
2
3

Benefits of Generators
1.
Memory Efficiency: Generators produce values on-the-fly, which means they don't
require storing the entire sequence in memory. This makes them suitable for working
with large datasets or infinite sequences.
2.
3.
Lazy Evaluation: Generators employ lazy evaluation, meaning they generate values
only when requested. This can lead to performance improvements as computations
are deferred until necessary.
4.
5.
Simplified Code: Generators can lead to more concise and readable code, especially
when dealing with operations that can be expressed as a sequence of values.
6.

Generator Expressions

In addition to generator functions, Python also supports generator expressions, which


are similar to list comprehensions but produce values lazily. They are defined using
parentheses instead of square brackets.

python
Copy code
gen = (x ** 2 for x in range(5))

Conclusion

Generators are a powerful feature of Python that allow for memory-efficient iteration
over large datasets or infinite sequences. They are created using generator functions
or generator expressions and provide benefits such as memory efficiency, lazy
evaluation, and simplified code. By understanding and utilizing generators, you can
write more efficient and readable Python code.

MCQs

1. What is a generator in Python?


- A) A device for producing electricity
- B) A function that generates random numbers
- C) An iterator that lazily produces values on-the-fly
- D) A module for generating HTML code

**Answer: C) An iterator that lazily produces values on-the-fly**

2. Which keyword is used to define a generator function in Python?


- A) `def`
- B) `generator`
- C) `yield`
- D) `return`

**Answer: C) `yield`**

3. What does the `yield` keyword do in a generator function?


- A) Ends the function's execution
- B) Returns a value to the caller and pauses execution
- C) Generates an error
- D) Prints the value to the console

**Answer: B) Returns a value to the caller and pauses execution**

4. Which of the following statements is true about generators?


- A) They store all the values in memory at once
- B) They produce values only when requested
- C) They are not iterable
- D) They are used for random number generation

**Answer: B) They produce values only when requested**

5. Which Python data structure is typically used to create generators?


- A) Lists
- B) Tuples
- C) Sets
- D) Functions

**Answer: D) Functions**

6. What happens when a generator function is called?


- A) It returns a list of values
- B) It returns a generator object
- C) It raises an error
- D) It executes all the code inside the function immediately

**Answer: B) It returns a generator object**

7. How are generator expressions defined in Python?


- A) Using square brackets `[ ]`
- B) Using curly braces `{ }`
- C) Using parentheses `( )`
- D) Using angle brackets `< >`

**Answer: C) Using parentheses `( )`**

8. What is the advantage of using generators over lists?


- A) Generators are faster
- B) Generators are memory-efficient
- C) Generators can store more data
- D) Generators support random access

**Answer: B) Generators are memory-efficient**

9. Which keyword is used to iterate over the elements of a generator?


- A) `for`
- B) `while`
- C) `iterate`
- D) `next`

**Answer: A) `for`**

10. How do you create an infinite generator in Python?


- A) By using a `while` loop
- B) By specifying a large range
- C) By using the `yield` keyword without a stop condition
- D) By using the `infinity` keyword
**Answer: C) By using the `yield` keyword without a stop condition**

11. Which method is used to advance a generator to the next value?


- A) `advance()`
- B) `next()`
- C) `move()`
- D) `forward()`

**Answer: B) `next()`**

12. What happens if you try to iterate over an exhausted generator?


- A) It raises a StopIteration error
- B) It returns `None`
- C) It restarts the generator
- D) It prints a warning message

**Answer: A) It raises a StopIteration error**

13. Can you pass arguments to a generator function?


- A) Yes
- B) No

**Answer: A) Yes**

14. Which of the following is NOT a benefit of using generators?


- A) Memory efficiency
- B) Lazy evaluation
- C) Code obfuscation
- D) Simplified code

**Answer: C) Code obfuscation**

15. What is the output of the following code snippet?


```python
def my_gen():
yield 1
yield 2
yield 3

gen = my_gen()
print(next(gen))
print(next(gen))
print(next(gen))
```
- A) 1 2 3
- B) 1 1 1
- C) 1 2 3 None
- D) Error: StopIteration

**Answer: A) 1 2 3**

16. Which of the following statements is true about generator objects?


- A) They can be indexed like lists
- B) They cannot be passed as arguments to functions
- C) They retain their state between iterations
- D) They can only yield one value
**Answer: C) They retain their state between iterations**

17. Which of the following statements is true about generator functions?


- A) They cannot contain any regular Python code
- B) They always return a value
- C) They must contain at least one yield statement
- D) They cannot accept arguments

**Answer: C) They must contain at least one yield statement**

18. What is the output of the following code snippet?


```python
def count_up_to(n):
count = 0
while count <= n:
yield count
count += 1

gen = count_up_to(3)
for num in gen:
print(num, end=" ")
```
- A) 0 1 2 3
- B) 1 2 3
- C) 0 1 2
- D) Error: StopIteration

**Answer: A) 0 1 2 3**

19. Which function is used to check if an object is a generator?


- A) `is_generator()`
- B) `type()`
- C) `isinstance()`
- D) `hasattr()`

**Answer: C) `isinstance()`**

20. What is the main advantage of using a generator expression over a list comprehension?
- A) Generators are faster to execute
- B) Generator expressions return a list
- C) Generator expressions are more readable
- D) There is no advantage; they are equivalent

**Answer: A) Generators are faster to execute**

21. Which of the following statements is true about generator expressions?


- A) They support random access
- B) They can be multi-line
- C) They always return a list
- D) They are defined using square brackets `[ ]`

**Answer: B) They can be multi-line**

22. What is the output of the following code snippet?


```python
gen = (x for x in range(3))
print(sum(gen))
```
- A) 0
- B) 3
- C) 6
- D) Error: StopIteration

**Answer: C

) 6**

23. Which of the following statements about generator objects is false?


- A) They can be used only once
- B) They cannot be serialized
- C) They can be stored in lists or tuples
- D) They can be shared among multiple threads safely

**Answer: D) They can be shared among multiple threads safely**

24. How do you create a generator function that generates Fibonacci numbers indefinitely?
- A) Using a `for` loop
- B) Using a `while` loop
- C) Using recursion
- D) Using a list comprehension

**Answer: B) Using a `while` loop**

25. What is the primary purpose of the `yield from` statement in Python?
- A) To return a value from a generator function
- B) To yield values from another iterable in a generator function
- C) To exit from a generator function
- D) To create a recursive generator

**Answer: B) To yield values from another iterable in a generator function**

26. Which method is used to close a generator and free up resources?


- A) `close()`
- B) `exit()`
- C) `end()`
- D) `stop()`

**Answer: A) `close()`**

27. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
return "Done"

gen = my_gen()
for num in gen:
print(num)
```
- A) 0 1 2
- B) 0 1 2 Done
- C) Error: StopIteration
- D) 0 1 2 None

**Answer: A) 0 1 2**

28. Which keyword is used to resume execution of a generator?


- A) `resume`
- B) `continue`
- C) `yield`
- D) `next`

**Answer: D) `next`**

29. Can a generator function return a value explicitly using the `return` statement?
- A) Yes
- B) No

**Answer: A) Yes**

30. What is the advantage of using the `yield from` statement over a nested loop in a generator
function?
- A) It improves performance
- B) It simplifies the code
- C) It allows for parallel execution
- D) There is no advantage

**Answer: B) It simplifies the code**

31. Which of the following is NOT a built-in function related to generators in Python?
- A) `next()`
- B) `yield()`
- C) `sum()`
- D) `close()`

**Answer: B) `yield()`**

32. How do you create a generator expression that generates squares of numbers from 1 to 10?
- A) `(x ** 2 for x in range(1, 11))`
- B) `[x ** 2 for x in range(1, 11)]`
- C) `{x ** 2 for x in range(1, 11)}`
- D) `<x ** 2 for x in range(1, 11)>`

**Answer: A) `(x ** 2 for x in range(1, 11))`**

33. Which of the following statements is true about generator expressions?


- A) They return a list
- B) They are more memory-efficient than list comprehensions
- C) They support item assignment
- D) They cannot be used as arguments to functions

**Answer: B) They are more memory-efficient than list comprehensions**

34. What is the primary difference between a generator function and a normal function?
- A) Generator functions always return a value
- B) Generator functions contain one or more `yield` statements
- C) Generator functions cannot accept arguments
- D) Generator functions can only be called once
**Answer: B) Generator functions contain one or more `yield` statements**

35. Which method is used to retrieve the current state of a generator?


- A) `state()`
- B) `current_state()`
- C) `__state__()`
- D) `__iter__()`

**Answer: D) `__iter__()`**

36. What is the output of the following code snippet?


```python
def my_gen():
yield 1
yield 2
yield 3

gen = my_gen()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen, "Done"))
```
- A) 1 2 3 Done
- B) 1 2 3 Error: StopIteration
- C) 1 2 3 None
- D) Error: StopIteration

**Answer: A) 1 2 3 Done**

37. Which of the following statements is true about generator objects?


- A) They cannot be used in a `for` loop
- B) They support random access
- C) They can be serialized using the `pickle` module
- D) They are immutable

**Answer: C) They can be serialized using the `pickle` module**

38. How do you create a generator that generates even numbers indefinitely?
- A) `def even_numbers(): while True: yield i if i % 2 == 0 else i += 1`
- B) `def even_numbers(): while True: yield i if i % 2 == 0 else i += 2`
- C) `def even_numbers(): i = 0 while True: yield i i += 2`
- D) `def even_numbers(): for i in range(2, float('inf'), 2): yield i`

**Answer: C) `def even_numbers(): i = 0 while True: yield i i += 2`**

39. Which of the following statements is true about generator expressions?


- A) They return a list
- B) They are evaluated eagerly
- C) They cannot contain conditionals
- D) They are enclosed in square brackets `[ ]`

**Answer: D) They are enclosed in square brackets `[ ]`**

40. What is the purpose of the `close()` method in generators?


- A) To close the generator and prevent further iteration
- B) To free up resources associated with the generator
- C) To raise a StopIteration error
- D) To restart the generator

**Answer: A) To close the generator and prevent further iteration**

41. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i

gen = my_gen()
print(len(gen))
```
- A) 3
- B) Error: TypeError
- C) 0
- D) None

**Answer: B) Error

: TypeError**

42. Which of the following statements is true about the `yield` keyword in generator functions?
- A) It can only be used once in a function
- B) It returns a value to the caller and pauses execution
- C) It terminates the function's execution immediately
- D) It is equivalent to the `return` keyword

**Answer: B) It returns a value to the caller and pauses execution**

43. How do you create a generator expression that generates the first 5 multiples of 3?
- A) `(i for i in range(3, 16) if i % 3 == 0)`
- B) `(i * 3 for i in range(5))`
- C) `(i * 3 for i in range(1, 6))`
- D) `(i for i in range(5) if i % 3 == 0)`

**Answer: C) `(i * 3 for i in range(1, 6))`**

44. Which method is used to restart a generator from the beginning?


- A) `reset()`
- B) `restart()`
- C) `start()`
- D) Generators cannot be restarted

**Answer: D) Generators cannot be restarted**

45. What is the output of the following code snippet?


```python
def my_gen():
yield 1
return "Done"
yield 2

gen = my_gen()
for num in gen:
print(num)
```
- A) 1
- B) 1 Done
- C) Error: StopIteration
- D) 1 2

**Answer: A) 1**

46. Which of the following statements is true about generator expressions?


- A) They are more memory-efficient than generator functions
- B) They support multiple `yield` statements
- C) They are enclosed in curly braces `{ }`
- D) They are evaluated eagerly

**Answer: D) They are evaluated eagerly**

47. What is the output of the following code snippet?


```python
def my_gen():
yield from range(3)

gen = my_gen()
for num in gen:
print(num, end=" ")
```
- A) 0 1 2
- B) 0 1 2 3
- C) Error: StopIteration
- D) 1 2 3

**Answer: A) 0 1 2**

48. Which method is used to check if a value is a generator object?


- A) `isgenerator()`
- B) `type()`
- C) `isinstance()`
- D) `hasattr()`

**Answer: A) `isgenerator()`**

49. How do you create a generator expression that generates all uppercase letters of the alphabet?
- A) `(chr(i) for i in range(ord('A'), ord('Z') + 1))`
- B) `(chr(i) for i in range(ord('a'), ord('z') + 1))`
- C) `(chr(i) for i in range(65, 91))`
- D) `[chr(i) for i in range(ord('A'), ord('Z') + 1)]`

**Answer: A) `(chr(i) for i in range(ord('A'), ord('Z') + 1))`**

50. What is the primary difference between a generator function and a normal function?
- A) Generator functions contain one or more `yield` statements
- B) Generator functions cannot accept arguments
- C) Generator functions always return a value
- D) Generator functions can only be called once

**Answer: A) Generator functions contain one or more `yield` statements**

51. Which of the following is NOT a built-in function related to generators in Python?
- A) `close()`
- B) `send()`
- C) `sum()`
- D) `next()`

**Answer: C) `sum()`**

52. How do you create a generator expression that generates the squares of even numbers from 1 to
10?
- A) `(x ** 2 for x in range(1, 11) if x % 2 == 0)`
- B) `(x ** 2 for x in range(2, 11, 2))`
- C) `(x ** 2 for x in range(1, 11) if x % 2 == 1)`
- D) `(x ** 2 for x in range(1, 11))`

**Answer: B) `(x ** 2 for x in range(2, 11, 2))`**

53. Which of the following is a valid way to stop a generator prematurely?


- A) Using the `return` keyword
- B) Using the `stop` method
- C) Using the `break` keyword
- D) Using the `close` method

**Answer: A) Using the `return` keyword**

54. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
yield from range(3, 6)

gen = my_gen()
for num in gen:
print(num, end=" ")
```
- A) 0 1 2 3 4 5
- B) 0 1 2 3 4 5 6
- C) Error: StopIteration
- D) 1 2 3 4 5

**Answer: A) 0 1 2 3 4 5**

55. Which of the following statements is true about generator objects?


- A) They can be copied using the `copy` method
- B) They can be converted to lists using the `list` constructor
- C) They can only be iterated once
- D) They are immutable

**Answer: C) They can only be iterated once**

56. What is the purpose of the `send()` method in generators?


- A) To send data to the generator
- B) To terminate the generator
- C) To retrieve the current state of the generator
- D) To advance the generator to the next value

**Answer: A) To send data to the generator**


57. Which of the following statements is true about generator expressions?
- A) They always return a list
- B) They can be nested inside other generator expressions
- C) They support item assignment
- D) They are defined using square brackets `[ ]`

**Answer: B) They can be nested inside other generator expressions**

58. How do you create a generator expression that generates all lowercase letters of the alphabet?
- A) `(chr(i) for i in range(ord('A'), ord('Z') + 1))`
- B) `(

chr(i) for i in range(ord('a'), ord('z') + 1))`


- C) `(chr(i) for i in range(97, 123))`
- D) `[chr(i) for i in range(ord('a'), ord('z') + 1)]`

**Answer: B) `(chr(i) for i in range(ord('a'), ord('z') + 1))`**

59. What is the output of the following code snippet?


```python
def my_gen():
yield from "hello"

gen = my_gen()
print(list(gen))
```
- A) ['h', 'e', 'l', 'l', 'o']
- B) ['hello']
- C) ['h', 'e', 'l', 'l', 'o', '']
- D) Error: StopIteration

**Answer: A) ['h', 'e', 'l', 'l', 'o']**

60. Which of the following is NOT a benefit of using generators in Python?


- A) Memory efficiency
- B) Lazy evaluation
- C) Simplicity of code
- D) Random access

**Answer: D) Random access**

61. What is the output of the following code snippet?


```python
def my_gen():
yield from range(3)

gen = my_gen()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
```
- A) 0 1 2 Error: StopIteration
- B) 0 1 2 3
- C) 0 1 2 None
- D) Error: StopIteration
**Answer: A) 0 1 2 Error: StopIteration**

62. Which of the following statements is true about the `send()` method in generators?
- A) It is used to send a value to the generator and return the next value
- B) It is used to send a value to the generator and retrieve the current state
- C) It is used to terminate the generator
- D) It is used to restart the generator from the beginning

**Answer: A) It is used to send a value to the generator and return the next value**

63. How do you create a generator expression that generates the first 5 prime numbers?
- A) `(i for i in range(2, 12) if all(i % j != 0 for j in range(2, i)))`
- B) `(i for i in range(5) if i in [2, 3, 5, 7, 11])`
- C) `(i for i in range(5) if i % 2 != 0)`
- D) `(i for i in range(2, 12) if i % 2 != 0)`

**Answer: A) `(i for i in range(2, 12) if all(i % j != 0 for j in range(2, i)))`**

64. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
return "Done"

gen = my_gen()
print(list(gen))
```
- A) [0, 1, 2, "Done"]
- B) [0, 1, 2]
- C) Error: StopIteration
- D) [0, 1, 2, None]

**Answer: A) [0, 1, 2, "Done"]**

65. Which of the following statements is true about generator expressions?


- A) They return a list
- B) They support random access
- C) They are more memory-efficient than list comprehensions
- D) They are defined using square brackets `[ ]`

**Answer: C) They are more memory-efficient than list comprehensions**

66. What is the output of the following code snippet?


```python
def my_gen():
yield 1
yield 2
yield 3

gen = my_gen()
for _ in range(4):
print(next(gen, "Done"), end=" ")
```
- A) 1 2 3 Done
- B) 1 2 3 None
- C) Error: StopIteration
- D) 1 2 3

**Answer: A) 1 2 3 Done**

67. Which of the following statements is true about generator functions?


- A) They always return a value
- B) They must contain at least one `return` statement
- C) They cannot contain regular Python code
- D) They must contain at least one `yield` statement

**Answer: D) They must contain at least one `yield` statement**

68. How do you create a generator expression that generates the squares of numbers from 1 to 10?
- A) `(x ** 2 for x in range(1, 11))`
- B) `[x ** 2 for x in range(1, 11)]`
- C) `{x ** 2 for x in range(1, 11)}`
- D) `<x ** 2 for x in range(1, 11)>`

**Answer: A) `(x ** 2 for x in range(1, 11))`**

69. What is the purpose of the `close()` method in generators?


- A) To close the generator and prevent further iteration
- B) To raise a StopIteration error
- C) To restart the generator
- D) To free up resources associated with the generator

**Answer: A) To close the generator and prevent further iteration**

70. Which of the following statements is true about generator expressions?


- A) They always return a list
- B) They can be multi-line
- C) They support item assignment
- D) They are defined using square brackets `[ ]`

**Answer: B) They can be multi-line**

71. What is the output of the following code snippet?


```python
def my_gen():
yield 1
yield 2
yield 3

gen = my_gen()
print(len(gen))
```
- A) 3
- B) Error: TypeError
- C) 0
- D) None

**Answer: B) Error: TypeError**

72. Which of the following statements is true about generator expressions?


- A) They always return a list
- B) They support random access
- C) They are evaluated lazily
- D) They cannot contain conditionals

**Answer: C) They are evaluated lazily**

73. How do you create a generator expression that generates all uppercase letters of the alphabet?
- A) `(chr(i) for i in range(ord('A'), ord('Z') + 1))`
- B) `(chr(i) for i in

range(ord('a'), ord('z') + 1))`


- C) `(chr(i) for i in range(65, 91))`
- D) `[chr(i) for i in range(ord('A'), ord('Z') + 1)]`

**Answer: A) `(chr(i) for i in range(ord('A'), ord('Z') + 1))`**

74. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
yield from range(3, 6)

gen = my_gen()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
```
- A) 0 1 2 3
- B) 0 1 2 3 4 5
- C) Error: StopIteration
- D) 1 2 3 4 5

**Answer: A) 0 1 2 3**

75. Which of the following is NOT a benefit of using generators in Python?


- A) Memory efficiency
- B) Lazy evaluation
- C) Simplicity of code
- D) Random access

**Answer: D) Random access**

76. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
return "Done"

gen = my_gen()
print(list(gen))
```
- A) [0, 1, 2, "Done"]
- B) [0, 1, 2]
- C) Error: StopIteration
- D) [0, 1, 2, None]
**Answer: A) [0, 1, 2, "Done"]**

77. Which of the following statements is true about generator expressions?


- A) They return a list
- B) They support random access
- C) They are more memory-efficient than list comprehensions
- D) They are defined using square brackets `[ ]`

**Answer: C) They are more memory-efficient than list comprehensions**

78. What is the output of the following code snippet?


```python
def my_gen():
yield 1
yield 2
yield 3

gen = my_gen()
for _ in range(4):
print(next(gen, "Done"), end=" ")
```
- A) 1 2 3 Done
- B) 1 2 3 None
- C) Error: StopIteration
- D) 1 2 3

**Answer: A) 1 2 3 Done**

79. Which of the following statements is true about generator functions?


- A) They always return a value
- B) They must contain at least one `return` statement
- C) They cannot contain regular Python code
- D) They must contain at least one `yield` statement

**Answer: D) They must contain at least one `yield` statement**

80. How do you create a generator expression that generates the squares of numbers from 1 to 10?
- A) `(x ** 2 for x in range(1, 11))`
- B) `[x ** 2 for x in range(1, 11)]`
- C) `{x ** 2 for x in range(1, 11)}`
- D) `<x ** 2 for x in range(1, 11)>`

**Answer: A) `(x ** 2 for x in range(1, 11))`**

81. What is the purpose of the `close()` method in generators?


- A) To close the generator and prevent further iteration
- B) To raise a StopIteration error
- C) To restart the generator
- D) To free up resources associated with the generator

**Answer: A) To close the generator and prevent further iteration**

82. Which of the following statements is true about generator expressions?


- A) They always return a list
- B) They can be multi-line
- C) They support item assignment
- D) They are defined using square brackets `[ ]`

**Answer: B) They can be multi-line**

83. What is the output of the following code snippet?


```python
def my_gen():
yield 1
yield 2
yield 3

gen = my_gen()
print(len(gen))
```
- A) 3
- B) Error: TypeError
- C) 0
- D) None

**Answer: B) Error: TypeError**

84. Which of the following statements is true about generator expressions?


- A) They always return a list
- B) They support random access
- C) They are evaluated lazily
- D) They cannot contain conditionals

**Answer: C) They are evaluated lazily**

85. How do you create a generator expression that generates all uppercase letters of the alphabet?
- A) `(chr(i) for i in range(ord('A'), ord('Z') + 1))`
- B) `(chr(i) for i in range(ord('a'), ord('z') + 1))`
- C) `(chr(i) for i in range(65, 91))`
- D) `[chr(i) for i in range(ord('A'), ord('Z') + 1)]`

**Answer: A) `(chr(i) for i in range(ord('A'), ord('Z') + 1))`**

86. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
yield from range(3, 6)

gen = my_gen()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
```
- A) 0 1 2 3
- B) 0 1 2 3 4 5
- C) Error: StopIteration
- D) 1 2 3 4 5

**Answer: A)
0 1 2 3**

87. Which of the following is NOT a benefit of using generators in Python?


- A) Memory efficiency
- B) Lazy evaluation
- C) Simplicity of code
- D) Random access

**Answer: D) Random access**

88. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
return "Done"

gen = my_gen()
print(list(gen))
```
- A) [0, 1, 2, "Done"]
- B) [0, 1, 2]
- C) Error: StopIteration
- D) [0, 1, 2, None]

**Answer: A) [0, 1, 2, "Done"]**

89. Which of the following statements is true about generator expressions?


- A) They return a list
- B) They support random access
- C) They are more memory-efficient than list comprehensions
- D) They are defined using square brackets `[ ]`

**Answer: C) They are more memory-efficient than list comprehensions**

90. What is the output of the following code snippet?


```python
def my_gen():
yield 1
yield 2
yield 3

gen = my_gen()
for _ in range(4):
print(next(gen, "Done"), end=" ")
```
- A) 1 2 3 Done
- B) 1 2 3 None
- C) Error: StopIteration
- D) 1 2 3

**Answer: A) 1 2 3 Done**

91. Which of the following statements is true about generator functions?


- A) They always return a value
- B) They must contain at least one `return` statement
- C) They cannot contain regular Python code
- D) They must contain at least one `yield` statement

**Answer: D) They must contain at least one `yield` statement**

92. How do you create a generator expression that generates the squares of numbers from 1 to 10?
- A) `(x ** 2 for x in range(1, 11))`
- B) `[x ** 2 for x in range(1, 11)]`
- C) `{x ** 2 for x in range(1, 11)}`
- D) `<x ** 2 for x in range(1, 11)>`

**Answer: A) `(x ** 2 for x in range(1, 11))`**

93. What is the purpose of the `close()` method in generators?


- A) To close the generator and prevent further iteration
- B) To raise a StopIteration error
- C) To restart the generator
- D) To free up resources associated with the generator

**Answer: A) To close the generator and prevent further iteration**

94. Which of the following statements is true about generator expressions?


- A) They always return a list
- B) They can be multi-line
- C) They support item assignment
- D) They are defined using square brackets `[ ]`

**Answer: B) They can be multi-line**

95. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
return "Done"

gen = my_gen()
print(len(gen))
```
- A) 3
- B) Error: TypeError
- C) 0
- D) None

**Answer: B) Error: TypeError**

96. Which of the following statements is true about generator expressions?


- A) They always return a list
- B) They support random access
- C) They are evaluated lazily
- D) They cannot contain conditionals

**Answer: C) They are evaluated lazily**

97. How do you create a generator expression that generates all uppercase letters of the alphabet?
- A) `(chr(i) for i in range(ord('A'), ord('Z') + 1))`
- B) `(chr(i) for i in range(ord('a'), ord('z') + 1))`
- C) `(chr(i) for i in range(65, 91))`
- D) `[chr(i) for i in range(ord('A'), ord('Z') + 1)]`

**Answer: A) `(chr(i) for i in range(ord('A'), ord('Z') + 1))`**

98. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
yield from range(3, 6)

gen = my_gen()
print(next(gen))
print(next(gen))
print(next(gen))
print(next(gen))
```
- A) 0 1 2 3
- B) 0 1 2 3 4 5
- C) Error: StopIteration
- D) 1 2 3 4 5

**Answer: A) 0 1 2 3**

99. Which of the following is NOT a benefit of using generators in Python?


- A) Memory efficiency
- B) Lazy evaluation
- C) Simplicity of code
- D) Random access

**Answer: D) Random access**

100. What is the output of the following code snippet?


```python
def my_gen():
for i in range(3):
yield i
return "Done"

gen = my_gen()
print(list(gen))
```
- A) [0, 1, 2, "Done"]
- B) [0, 1, 2]
- C) Error: StopIteration
- D) [0, 1, 2, None]

**Answer: A) [0, 1, 2, "Done"]**

You might also like