Skip to content

Multiple assignment and tuple swapping [ref]

Problem

  • Assign a = 1 and b = 2 in one statement.
  • Swap a = 1 and b = 2 without a temporary variable.
  • Unpack (3, 4) into x and y.
  • Update prev2 = 1 and prev1 = 2 simultaneously to the old prev1 and their sum.
  • Unpack the first value and remaining values of (1, 2, 3).

Python solution

a, b = 1, 2
(a, b)  # (1, 2)

a, b = 1, 2
a, b = b, a
(a, b)  # (2, 1)

x, y = (3, 4)
(x, y)  # (3, 4)

prev2, prev1 = 1, 2
prev2, prev1 = prev1, prev2 + prev1
(prev2, prev1)  # (2, 3)

first, *rest = (1, 2, 3)
(first, rest)  # (1, [2, 3])