Question 160 of 498
PCEP Practice Question: Data Types, Variables, Basic I/O and Operators
A beginner Python learner writes a script to swap two numbers:
a = 10 b = 20 a = b b = a
print("a =", a, "b =", b)The output is "a = 20 b = 20". The learner expected "a = 20 b = 10". Which of the following is the most Pythonic way to fix the code?
⚠ Common exam trap
Python Institute often tests the misconception that any working swap is equally Pythonic, but the PCEP emphasizes idiomatic Python (PEP 8 style), making tuple unpacking the only correct answer despite other options being functionally correct.
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
✓
Use tuple unpacking: a, b = b, a
Tuple unpacking is the most Pythonic and idiomatic way to swap two variables. It leverages Python's ability to evaluate the right-hand side as a tuple before assignment, so the original values of `a` and `b` are captured simultaneously, avoiding the overwrite issue in the original code.
Answer analysis
Option-by-option breakdown
For each option: why learners choose it and why it is or isn't the right answer here.
- ✗
Use bitwise XOR: a ^= b; b ^= a; a ^= b
Why it's wrong here
This works only for integers and is less readable.
- ✓
Use tuple unpacking: a, b = b, a
Why this is correct
This is the standard Pythonic swap.
- ✗
Use a temporary variable: temp = a; a = b; b = temp
Why it's wrong here
This works but is not as concise as tuple unpacking.
- ✗
Use integer arithmetic: a = a + b; b = a - b; a = a - b
Why it's wrong here
This works but is error-prone and less readable.
About these practice questions
Courseiva creates original exam-style practice questions with explanations and wrong-answer analysis. It does not publish real exam questions, exam dumps, or protected exam content. Learn why practice questions differ from exam dumps →
Last reviewed: Jun 30, 2026
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.
Question Discussion
Share a tip, memory trick, or ask about the reasoning behind this question. Do not post real exam questions, leaked content, braindumps, or copyrighted exam material. Comments are moderated and may be removed without notice.
Sign in to join the discussion.