Skip to content

Multiple Assignment

Many Values to Multiple Variables

We can assign multiple values to multiple variables in one line. This is called multiple assignment.

Example:

variable.py
# Multiple assignment
a, b, c = 10, 20.5, "Hello, World!"
print(a, b, c)
variable.py
# Multiple assignment
a, b, c = 10, 20.5, "Hello, World!"
print(a, b, c)

Output

command
C:\Users\Your Name> python variable.py
10 20.5 Hello, World!
command
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:

variable.py
# One value to multiple variables
a = b = c = 10
print(a, b, c)
variable.py
# One value to multiple variables
a = b = c = 10
print(a, b, c)

Output

command
C:\Users\Your Name> python variable.py
10 10 10
command
C:\Users\Your Name> python variable.py
10 10 10

Multiple Values to One Variable

We can assign multiple values to one variable in one line. This is called multiple values to one variable.

Example:

variable.py
# Multiple values to one variable
a = 10, 20, 30
print(a)
variable.py
# Multiple values to one variable
a = 10, 20, 30
print(a)

Output

command
C:\Users\Your Name> python variable.py
(10, 20, 30)
command
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:

variable.py
# Unpacking a tuple
a = 10, 20, 30
x, y, z = a
print(x, y, z)
variable.py
# Unpacking a tuple
a = 10, 20, 30
x, y, z = a
print(x, y, z)

Output

command
C:\Users\Your Name> python variable.py
10 20 30
command
C:\Users\Your Name> python variable.py
10 20 30

Unpacking a List

We can unpack a list in multiple variables. This is called unpacking a list.

Example:

variable.py
# Unpacking a list
a = [10, 20, 30]
x, y, z = a
print(x, y, z)
variable.py
# Unpacking a list
a = [10, 20, 30]
x, y, z = a
print(x, y, z)

Output

command
C:\Users\Your Name> python variable.py
10 20 30
command
C:\Users\Your Name> python variable.py
10 20 30

Was this page helpful?

Let us know how we did