4️⃣

14.4 Variable Swapping

Variable Swapping

Variable swapping is the switching of the values of two variables. Normally, you would need a third variable to facilitate the swap of two elements. The reason for this is that after you set the first element to the second element and you try to set the second element to the first element, the second element is the same as the first element. Take a look at the code for the variable swap:
# Switching 2 and 3 list1 = [1, 2, 3, 4, 5] temp = list1[1] list1[1] = list1[2] list1[2] = temp print(list1) # prints [1, 3, 2, 4, 5]
As you can see, we needed a temp (temporary) variable in order to swap list1[1] and list1[2].
But, Python has a special way to swap elements. It's a feature that allows you to swap elements using one line of code:
list1[1], list1[2] = list1[2], list1[1] print(list1) # prints [1, 3, 2, 4, 5]
As you see, list1[1] is now 3, and list1[2] is now 2.
 
We can swap more than 2 elements at the same time. Let's use the original list1 again:
list1[0], list1[1], list1[2] = list1[1], list1[2], list1[0] print(list1) # prints [2, 3, 1, 4, 5]
As you see, list1[2] is now 1, list1[0] is now 2, and list1[1] is now 3
View code on GitHub.

Next Section

5️⃣
14.5 Zip
 
⚖️
Copyright © 2021 Code 4 Tomorrow. All rights reserved. The code in this course is licensed under the MIT License. If you would like to use content from any of our courses, you must obtain our explicit written permission and provide credit. Please contact classes@code4tomorrow.org for inquiries.