PCEP Practice Question: Data Types, Variables, Basic I/O and Operators
A programmer needs to swap the values of two variables a and b without using a temporary variable. Which approach works in Python?
⚠ Common exam trap
Python Institute often tests the misconception that simple sequential assignment (a = b; b = a) works for swapping, leading candidates to overlook Python's tuple unpacking mechanism.
Answer choices
Why each option matters
Answer the question above first, then reveal the full breakdown to understand why each option is right or wrong.
Correct answer & explanation
✓
a, b = b, a
Python supports tuple unpacking, which allows the values of a and b to be swapped in a single atomic operation: a, b = b, a. This works by creating a tuple (b, a) on the right-hand side, then unpacking it into the variables on the left, effectively swapping the values without a temporary variable.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
a = b; b = a
Why it's wrong here
Assigning a = b overwrites a's original value before b = a runs, so both variables end up holding b's value. It is tempting as the intuitive reading of 'swap', but Python's actual no-temporary-variable idiom is tuple assignment: a, b = b, a.
- ✓
a, b = b, a
Why this is correct
Python evaluates the right-hand tuple (b, a) fully before assigning to the left-hand targets, so both original values are captured prior to rebinding. This tuple-unpacking swap needs no temporary variable and works for any assignable targets.
- ✗
a = a ^ b; b = a ^ b; a = a ^ b
Why it's wrong here
XOR swapping requires integers; applying ^ to strings, floats or lists raises a TypeError in Python. It is tempting because the three XOR operations do restore the original values bitwise, but Python's tuple assignment a, b = b, a works for every type.
- ✗
a = b + a; b = a - b; a = a - b
Why it's wrong here
Arithmetic swapping works only for numbers and corrupts values when a and b are strings, lists or other types; Python's dynamic typing makes this fragile. It is tempting because the addition and subtraction cancel correctly for integers, but tuple assignment handles any type.
Go deeper
Related to this question
About these practice questions
One of 482 original PCEP practice questions on Courseiva, each with a full explanation and wrong-answer analysis — not exam dumps or protected exam content. Learn why practice questions differ from exam dumps →
JA
Written by Johnson Ajibi, MSc IT Security
Senior Network & Security Engineer · founder of Courseiva
This PCEP practice question is part of Courseiva's free Python Institute certification practice question bank. Courseiva provides original exam-style practice questions with explanations, topic-based practice, mock exams, readiness tracking, and study analytics to help learners prepare for the PCEP exam.