Swapping Variables
Part of the Logic & Flow section of Coddy's Python journey — lesson 3 of 78.
Swapping variables is a common operation where the values of two variables are exchanged. Python offers a simple and elegant way to swap variables without needing a temporary variable, unlike many other programming languages.
Traditional Method (Using a Temporary Variable):
a = 10
b = 20
temp = a
a = b
b = temp
print(a) # Output: 20
print(b) # Output: 10Pythonic Way (Simultaneous Assignment):
a = 10
b = 20
a, b = b, a
print(a) # Output: 20
print(b) # Output: 10In the Pythonic way, the values of b and a are simultaneously assigned to a and b, respectively. This approach is more readable and doesn't require any additional variables.
Challenge
EasyWrite a Python program to swap the values of two variables without using a temporary variable. Initialize two variables, x and y, with the values 5 and 10 respectively. Swap their values and then print them.
Cheat sheet
Python allows swapping variables using simultaneous assignment without needing a temporary variable.
Traditional method using a temporary variable:
a = 10
b = 20
temp = a
a = b
b = tempPythonic way using simultaneous assignment:
a = 10
b = 20
a, b = b, aThe simultaneous assignment approach is more readable and doesn't require additional variables.
Try it yourself
# Initialize variables x and y
# Swap the values of x and y
# Print the swapped values
print(f"x: {x}")
print(f"y: {y}")This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Logic & Flow
1Variables Exploration
ConstantsMultiple Variable AssignmentsSwapping VariablesPlaceholder VariablesRound NumbersList Casting4Contact Book Application
Display MenuAdd Contact7Sets Part 2
Mathematical Operations Part 1Mathematical Operations Part 2Recap - Treasure HuntSubsets and SupersetsIterating Over SetsRecap - Tournament Tracker2Dictionaries Part 1
What is a Dictionary?Creating a DictionaryAccessing ValuesModifying DictionariesRecap - Recipe Manager5Advanced Decision Making
Ternary OperatorMembership ChecksIdentity ChecksIndentation ErrorsRecap - Vacation Filter8Student Records Manager
Project OverviewAdd Student11Advanced Functions
Returning Multiple ValuesLambda Functions Part 1Lambda Functions Part 2Recap Challenge - Lambda SortRecursive Functions Part 1Recursive Functions Part 2Recap - Sum Nested List14Higher-Order Functions
The Map FunctionThe Filter FunctionRecap - Email ValidatorRecap - Number Processor3Dictionaries Part 2
Dictionary MethodsNested DictionariesChecking for KeysLooping Through DictionariesRecap - Frequency Counter9Advanced Data Aggregation
Using SumFinding Minimum and MaximumSorting Data EfficientlyRecap - Dictionary Sorter