What will be printed by the following Python code snippet?

x = [1, 2, 3]
y = [4, 5, 6]
print([a + b for a, b in zip(x, y)])

Answer and explanation

Correct answer: C. [5, 7, 9]

  1. Step 1: `zip(x, y)` pairs elements index by index: `(1, 4)`, `(2, 5)`, `(3, 6)`.
  2. Step 2: The comprehension computes `a + b` for each pair: , , , returning `[5, 7, 9]`.
Answer
[5, 7, 9].
Why not the others: `[1, 2, 3, 4, 5, 6]` is list concatenation `x + y`; `[4, 10, 18]` computes products `a * b`; `[(1, 4), ...]` is the raw zip output.

Practise more Algorithms and Python Programming.

Free questions with an explanation for every one, and full timed EmSAT Achieve (UAE) mock tests.

What will be printed by the following… | EmSAT Achieve (UAE)