We can assign multiple values to multiple variables or a single value to multiple variables.
Assign Multiple Values to Multiple Variables
We can easily assign multiple values to multiple variables in Python. For example:
text1, text2, text3 = 'Python', 'Java', 'PHP'
print(text1, text2, text3)
Python Java PHP
In this example, we created 3 variables and assigned 3 values to them. Instead of assigning a single variable, like text1 = 'Python', text2 = 'Java', text3 = 'PHP'
, we assign multiple variables in a single line. Here is a very important rule to remember: the number of variables should be the same as the number of values; otherwise, we will get an error. For example:
text1, text2, text3 = 'Python', 'Java'
print(text1, text2, text3)
ValueError: not enough values to unpack (expected 3, got 2)
So we get ValueError. It shows expected 3, got 2. Because we only assign two values for three variables. So it is very important to assign the same number of values to the same number of variables.
Assign One Value to Multiple Variables
In the upper example, we assign multiple values to multiple variables. However, if we want, we can assign a single value to multiple variables. For example:
text1 = text2 = text3 = 'Python'
print(text1)
print(text2)
print(text3)
Python
Python
Python
Here we assign a single value, 'Python'
to 3 variables (text1, text2, text3)
. Here is a difference, in this example, we use equal sign (=
) when creating the variables, and in the previous example, when we create variables text1, text2, text3
we use the comma (,) sign
. This is the difference to remember.
Now what if we assign multiple values in the same situation?
text1 = text2 = text3 = 'Python', 'Java'
print(text1)
print(text2)
print(text3)
('Python', 'Java')
('Python', 'Java')
('Python', 'Java')
Now each variable consists of multiple values. So we get the output in a tuple. A tuple is a data type in Python used to store multiple collections of values.
Assign Multiple Values to One Variable
In the upper example, we assign a single value to multiple variables. It is possible to do the exact opposite. We can assign multiple values to a single variable. For example:
text1 = 'Python', 'Java', 'PHP'
print(text1)
('Python', 'Java', 'PHP')
Here we create a single variable and assign multiple values to this variable. And this variable consists of all values as a tuple. We can check the data type with the help of the type()
function.
text1 = 'Python', 'Java', 'PHP'
print(text1)
print(type(text1))
('Python', 'Java', 'PHP')
<class 'tuple'>
So we get the output in a tuple.