ProgrammingVery hardGATE CS · Product-company placement
What is printed?
What is printed?
def f():
x = 0
def inc():
nonlocal x
x += 1
return x
return [inc() for _ in range(3)], x
print(f())- A. ([1, 2, 3], 0)
- B. ([1, 2, 3], 3)
- C. ([1, 1, 1], 3)
- D. ([1, 1, 1], 0)
Correct answer: B. ([1, 2, 3], 3)
The tuple elements are evaluated left to right: the comprehension runs inc three times first (each call updating the shared cell), so by the time x is read it is already 3.
More Python Programming questions
- What is printed? python def f(kw): return list(kw) print(f(b=1, a=2), f(dict(z=0), y=1), f({"1": 1}))
- What is printed? python class A: def getitem(self, k): return k a = A() print(a[1], a[1:3], a[::2], a[1, 2:3], a[...])
- What is printed? python print([int(t, 0) for t in " 12000 t-0b101 +7 ".split()])
- What is printed? python import sys print(sys.getintmaxstrdigits()) try: s = str(10 4300) except ValueError: print("too long")
- What is printed? python print(len(str(2 1000 5 1000)))
- What is printed? python rows = [(2, 'b'), (1, 'z'), (2, 'a'), (1, 'y')] print(sorted(rows, key=lambda t: (-t[0], t[1])))