ProgrammingVery hardProduct company OA

What is printed?

What is printed?
data = [5, 3, 8, 1]
out = []
while (n := len(data)) > 1:
    first, *data = data
    data[-1] += first
    out.append((n, data[-1]))
print(out, data)
  1. A. [(4, 6), (3, 9), (2, 17)] [17]
  2. B. [(4, 6), (3, 9), (2, 17)] [8, 17]
  3. C. [(3, 6), (2, 9), (1, 17)] [17]
  4. D. [(4, 6), (3, 11), (2, 19)] [19]

Correct answer: A. [(4, 6), (3, 9), (2, 17)] [17]

The walrus binds n to the length BEFORE the body shrinks the list. Star-unpacking builds a new list from the rest: first = 5, data = [3, 8, 1] → last becomes 6; first = 3, data = [8, 6] → 9; first = 8, data = [9] → 17. Then len is 1 and the loop stops. Output: [(4, 6), (3, 9), (2, 17)] [17]. The (3, …), (2, …), (1, …) option reads n after the unpacking.

More Python Programming questions

Exams that ask this topic