Iterators and Generators

Last Updated :
Discuss
Comments

Question 1

What does the yield keyword do in a Python function?

  • Exits the function immediately

  • Returns a list

  • Returns a value and pauses the function execution

  • Allocates memory dynamically

Question 2

What is the output of this code?

Python
def fun(m):
    for i in range(m):
        yield i

for n in fun(3):
    print(n, end=" ")


  • 1 2 3

  • 0 1 2

  • 0 1 2 3

  • Error

Question 3

Which built-in methods do generator objects support implicitly?

  • __getitem__()

  • __str__() and __len__()

  • __iter__() and __next__()

  • append() and pop()

Question 4

Which of the following statements is TRUE about generator expressions in Python?

  • They return a list

  • They are memory-efficient

  • They use square brackets

  • They require def keyword

Question 5

What is the output of the following generator expression?

Python
gen = (x * x for x in range(3))
print(list(gen))


  • [1, 2, 3]

  • [0, 1, 4]

  • [1, 4, 9]

  • Error

Question 6

Which keyword causes a generator function to pause and retain its state?

  • pause

  • return

  • yield

  • continue

Question 7

What will be the output of the following code?

Python
def my_gen():
    yield "Python"
    yield "Rocks"
g = my_gen()
print(next(g))
print(next(g))


  • Python\nRocks

  • Rocks\nPython

  • Error

  • None

Question 8

What happens if you call next() on a generator that has no more items to yield?

  • Returns None

  • Returns False

  • Raises StopIteration

  • Starts from beginning

Question 9

Which of the following is an application of generators in Python?

  • Searching binary trees

  • Memory-efficient data streaming

  • GUI design

  • Encryption

Question 10

What is the key advantage of using generators over lists when processing large files?

  • Faster writing to disk

  • Easier syntax

  • Lower memory usage

  • Allows indexing

There are 12 questions to complete.

Take a part in the ongoing discussion