Multiple Variable Assignments
Part of the Logic & Flow section of Coddy's Python journey — lesson 2 of 78.
In Python, you can assign values to multiple variables in a single line. This feature can make your code more concise and readable. Let's explore how to use multiple variable assignments effectively.
Basic Multiple Assignments:
a, b, c = 1, 2, 3
print(a) # Output: 1
print(b) # Output: 2
print(c) # Output: 3Assigning the same value to multiple variables:
x = y = z = 10
print(x) # Output: 10
print(y) # Output: 10
print(z) # Output: 10Assigning values from a list:
numbers = [4, 5, 6]
a, b, c = numbers
print(a) # Output: 4
print(b) # Output: 5
print(c) # Output: 6Challenge
EasyWrite a Python program that performs the following tasks:
- Assign values to three variables
name,age, andcityin a single line. Setnameto"Alice",ageto30, andcityto"New York". - Assign the value
100to three variablesx,y, andzin a single line. - Create a list named
colorscontaining the values"red","green", and"blue". Assign these values to three variablescolor1,color2, andcolor3in a single line.
Cheat sheet
You can assign values to multiple variables in a single line:
a, b, c = 1, 2, 3Assign the same value to multiple variables:
x = y = z = 10Assign values from a list:
numbers = [4, 5, 6]
a, b, c = numbersTry it yourself
# Assign values to name, age, and city
# Assign 100 to x, y, and z
# Create a list of colors and assign them to color1, color2, and color3
colors = ["red", "green", "blue"]
# Don't change the code below
print(f"Name: {name}, Age: {age}, City: {city}")
print(f"x: {x}, y: {y}, z: {z}")
print(f"Colors: {color1}, {color2}, {color3}")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