What is the correct syntax to swap two variables in Python?

Study for the PCEP Certified Entry-Level Python Programmer Exam. Access multiple choice questions and detailed explanations to enhance your learning. Prepare effectively for your certification!

The correct syntax to swap two variables in Python is to use the tuple unpacking feature, which allows for a concise and efficient swapping operation. The statement that achieves this swaps the values of variable_1 and variable_2 in a single line by creating a tuple on the right side of the assignment and unpacking it into the variables on the left side.

When you write variable_1, variable_2 = variable_2, variable_1, Python evaluates the right-hand side first, creating a tuple with the current values of variable_2 and variable_1. Then, it assigns the first element of the tuple to variable_1 and the second element to variable_2, effectively swapping their values.

This approach is not only syntactically elegant but also avoids the need for a temporary variable or multiple assignment statements, which can be more cumbersome and less readable. This method showcases the power of Python’s tuple unpacking and is a widely accepted idiom for swapping values in Python programming.

Subscribe

Get the latest from Examzify

You can unsubscribe at any time. Read our privacy policy