Skip to Content

Python Basics: How Does Python’s Simultaneous Assignment Rotate Variable Values?

What Is the Result of Swapping Variables Using Tuple Unpacking in Python?

Learn the powerful technique of simultaneous assignment in Python. This guide explains how tuple packing and unpacking allows you to rotate or swap the values of multiple variables in a single, elegant line of code without needing a temporary variable.

Question

What is the output of: a, b, c = 1, 2, 3; a, b, c = c, a, b; print(a, b, c)?

A. 1 2 3
B. 3 2 1
C. 2 3 1
D. 3 1 2

Answer

D. 3 1 2

Explanation

a←c, b←a(old), c←b(old) → 3 1 2.

This result is due to Python’s feature of simultaneous assignment, which relies on tuple unpacking. The key is that the entire right-hand side of the assignment is evaluated before any of the variables on the left-hand side are updated.

Here is a step-by-step breakdown:

  1. Initial Assignment: a, b, c = 1, 2, 3 sets a to 1, b to 2, and c to 3.
  2. Evaluation of the Right-Hand Side: In the line a, b, c = c, a, b, Python first evaluates the expression on the right. It uses the current values of c, a, and b to create a temporary tuple. At this moment, c is 3, a is 1, and b is 2. So, an implicit tuple (3, 1, 2) is created in memory.
  3. Simultaneous Assignment: Python then unpacks this temporary tuple (3, 1, 2) and assigns its values to the variables on the left, in order.
    • The first variable, a, gets the first value from the tuple, which is 3.
    • The second variable, b, gets the second value, which is 1.
    • The third variable, c, gets the third value, which is 2.
  4. Final Print: The print(a, b, c) statement then outputs the new values of the variables, which are 3 1 2.

This is a common “Pythonic” idiom for swapping or rotating variable values concisely.

Python Basics: Learn, Apply & Build Programs certification exam assessment practice question and answer (Q&A) dump including multiple choice questions (MCQ) and objective type questions, with detail explanation and reference available free, helpful to pass the Python Basics: Learn, Apply & Build Programs exam and earn Python Basics: Learn, Apply & Build Programs certificate.