Multiple Assignment
Many Values to Multiple Variables
We can assign multiple values to multiple variables in one line. This is called multiple assignment.
Example:
# Multiple assignment
a, b, c = 10, 20.5, "Hello, World!"
print(a, b, c)# Multiple assignment
a, b, c = 10, 20.5, "Hello, World!"
print(a, b, c)Output
C:\Users\Your Name> python variable.py
10 20.5 Hello, World!C:\Users\Your Name> python variable.py
10 20.5 Hello, World!One Value to Multiple Variables
We can assign one value to multiple variables in one line. This is called one value to multiple variables.
Example:
# One value to multiple variables
a = b = c = 10
print(a, b, c)# One value to multiple variables
a = b = c = 10
print(a, b, c)Output
C:\Users\Your Name> python variable.py
10 10 10C:\Users\Your Name> python variable.py
10 10 10Multiple Values to One Variable
We can assign multiple values to one variable in one line. This is called multiple values to one variable.
Example:
# Multiple values to one variable
a = 10, 20, 30
print(a)# Multiple values to one variable
a = 10, 20, 30
print(a)Output
C:\Users\Your Name> python variable.py
(10, 20, 30)C:\Users\Your Name> python variable.py
(10, 20, 30)In this case, the variable aa is a tuple.
Unpacking a Tuple
We can unpack a tuple in multiple variables. This is called unpacking a tuple.
Example:
# Unpacking a tuple
a = 10, 20, 30
x, y, z = a
print(x, y, z)# Unpacking a tuple
a = 10, 20, 30
x, y, z = a
print(x, y, z)Output
C:\Users\Your Name> python variable.py
10 20 30C:\Users\Your Name> python variable.py
10 20 30Unpacking a List
We can unpack a list in multiple variables. This is called unpacking a list.
Example:
# Unpacking a list
a = [10, 20, 30]
x, y, z = a
print(x, y, z)# Unpacking a list
a = [10, 20, 30]
x, y, z = a
print(x, y, z)Output
C:\Users\Your Name> python variable.py
10 20 30C:\Users\Your Name> python variable.py
10 20 30Extended Unpacking with **
When you do not know (or do not care) how many items are in the middle, a starred variable ** captures the rest as a list. This is called extended unpacking.
numbers = [1, 2, 3, 4, 5]
first, *rest = numbers
print(first, rest) # 1 [2, 3, 4, 5]
first, *middle, last = numbers
print(first, middle, last) # 1 [2, 3, 4] 5numbers = [1, 2, 3, 4, 5]
first, *rest = numbers
print(first, rest) # 1 [2, 3, 4, 5]
first, *middle, last = numbers
print(first, middle, last) # 1 [2, 3, 4] 5Swapping Variables
Multiple assignment gives Python an elegant one-line swap — no temporary variable needed. The right-hand side is built into a tuple first, then unpacked.
a, b = 5, 10
a, b = b, a
print(a, b) # 10 5a, b = 5, 10
a, b = b, a
print(a, b) # 10 5Try it: Multiple Assignment Exercises
Exercise 1 – Assign Same Value to Multiple Variables
Exercise 2 – Tuple Unpacking
Exercise 3 – Assign from a List
If this helped you, consider buying me a coffee ☕
Buy me a coffeeWas this page helpful?
Let us know how we did
