ProgrammingVery hardTCS NQT · Infosys · GATE CS
What is printed? a = [1, 2, 3]; b = [2, 3, 4] g = (x for x in a if x in b) a = [9, 2, 3]; b = [1, 9, 3] print(list(g))
- A. [2, 3]
- B. [1, 3]
- C. [9, 3]
- D. [1, 9, 3]
Correct answer: B. [1, 3]
In a generator expression only the outermost iterable (a) is evaluated immediately, so it still iterates over [1, 2, 3]. The condition x in b is evaluated lazily and sees the rebound b = [1, 9, 3], keeping 1 and 3.
More Python Programming questions
- What does this Python code print? def deco(tag): def wrap(fn): def inner(x): return "<" + tag + ">" + fn(x) + "</" + tag + ">" return…
- What does this Python code print? words = ["bb", "a", "ccc", "dd", "e", "fff"] print(sorted(words, key=len, reverse=True)[:3], min(words…
- What is printed? python def f(): for i in range(3): try: if i == 1: continue if i == 2: return 'ret' finally: print('f', i, end=' ')…
- What is printed? python class A: def f(self): return 'A' class B(A): def f(self): return 'B' + super().f() class C(A): def f(self): return…
- What is printed? python def gen(): x = yield 1 print('got', x) y = yield x 2 return y g = gen() print(next(g)) print(g.send(10)) try…
- What is printed? python funcs = [] for i in range(3): funcs.append(lambda x=i: x 10) funcs.append(lambda: i 10) print([f() for f in funcs])