Content · Programming · Python

Python Swapping Variables with Tuple Unpacking

Tuple unpacking lets you swap two variables without creating a third temporary variable. Python evaluates the right side before assigning the targets. Learn the essential ideas and try a practical example.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Tuple unpacking lets you swap two variables without creating a third temporary variable. Python evaluates the right side before assigning the targets.

Understanding the Concept


In many languages, swapping values requires a temporary name. Python can express the operation as first_value, second_value = second_value, first_value. The values on the right are evaluated using the original bindings, then assigned to the left. The same principle works for other multiple assignments and is useful for reading tuple-based data.

When and Why You Would Use This


The example starts with two labels and exchanges them. This is a value swap, not a character-by-character modification of the strings.

Practical Example


first_label = "left"
second_label = "right"
first_label, second_label = second_label, first_label
print(first_label, second_label)

Understanding the Example


The output is right left. Both right-hand values are obtained before Python rebinds the two names. There is no need to create a temporary variable manually.

Example Output


right left

Try It Yourself


Swap two numeric values and then swap them back. Print both states.

Common Beginner Mistakes


  • Writing assignments one after another and overwriting the original value before using it.
  • Thinking the swap modifies immutable string objects in place.
  • Using tuple unpacking without matching the number of values and targets.

Key Takeaways


  • Tuple unpacking supports concise simultaneous assignment.
  • Python evaluates the entire right-hand side before rebinding the names.
  • This makes swapping values simple and readable.
Share this resourceSend this page to someone who may find it useful.