ProgrammingHardGATE CS · Product-company placement
What is printed?
What is printed?
x = 1 g = (x * y for y in range(3)) x = 2 print(list(g))
- A. [0, 1, 2]
- B. [0, 2, 4]
- C. [0, 2, 2]
- D. []
Correct answer: B. [0, 2, 4]
Only the outermost iterable (range(3)) is evaluated when the generator expression is created; x is looked up each time an element is produced, by which point x is 2.
More Python Programming questions
- What is printed? python xs = [1, 2, 3] g = (a 10 + b for a in xs for b in xs) xs = [10, 20] print(sum(g))
- What is printed? python def g(): yield 1 yield 2 it = g() for v in it: print(v, end=" ") break for v in it: print(v, end=" ")…
- What is printed? python def g(): total = 0 while True: x = yield total if x is None: return total 100 total += x it = g() next(it)…
- What is printed? python def inner(): a = yield "x" b = yield "y" return (a, b) def outer(): r = yield from inner() yield r o = outer()…
- What is printed? python def g(): try: yield 1 yield 2 except KeyError: yield "caught" yield 3 it = g() print(next(it), it.throw(KeyError)…
- What is printed? python def g(): yield 1 raise StopIteration try: print(list(g())) except RuntimeError as e: print("RuntimeError")