Skip to content
Related Articles

Related Articles

Assigning multiple variables in one line in Python
  • Last Updated : 02 Dec, 2020

A variable is a named memory space that is used to store some data which will in-turn be used in some processing. All programing languages have some mechanism for variable declaration but one thing that stays common in all is the name and the data to be assigned to it. They are capable of storing values of data types.

Assignment operator(=) assigns the value provided to its right to the variable name given to its left. Given is the basic syntax of variable declaration:

Syntax:

var_name = value

Example:

a = 4

Assigning multiple variables in one line

Given above is the mechanism for assigning just variables in Python but it is possible to assign multiple variables at the same time. Python assigns values from right to left. When assigning multiple variables in a single line, different variable names are provided to the left of the assignment operator separated by a comma. The same goes for their respective values except they should to the right of the assignment operator.



While declaring variables in this fashion one must be careful with the order of the names and their corresponding value first variable name to the left of the assignment operator is assigned with the first value to its right and so on. 

Example 1:

Python3




a, b = 4, 8
print("value assigned to a")
print(a)
print("value assigned to b")
print(b)

Output:

value assigned to a
4
value assigned to b
8

Variable assignment in a single line can also be done for different data types.

Example 2:

Python3




print("assigning values of different datatypes")
a, b, c, d = 4, "geeks", 3.14, True
print(a)
print(b)
print(c)
print(d)

Output:

assigning values of different datatypes
4
geeks
3.14
True

Not just simple variable assignment, assignment after performing some operation can also be done in the same way.

Example 3:

Python3




a, b = 8, 3
add, pro = (a+b), (a*b)
print(add)
print(pro)

Output:

11
24

Example 4:

Python3




string = "Geeks"
a, b, c = string[0], string[1:4], string[4]
  
print(a)
print(b)
print(c)

Output:

G
eek
s

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :