Courseiva
Data Types, Variables, Basic I/O and OperatorsmediumMultiple ChoiceObjective-mapped

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

    Incorrect: both end up with same value.

  • a, b = b, a

    Why this is correct

    Correct: Python's tuple unpacking swaps values.

  • a = a ^ b; b = a ^ b; a = a ^ b

    Why it's wrong here

    Incorrect: works but not recommended; also fails for non-int.

  • a = b + a; b = a - b; a = a - b

    Why it's wrong here

    Incorrect: this only works for numbers and is error-prone.

About these practice questions

One of 498 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 →

How Courseiva writes practice questions · Editorial policy

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.