Set multiple variables in one line in Python

06-12-22 Ahmed Obaid 2827 0

​As we mentioned earlier, a variable is a piece of memory with a unique name that is used to hold the data that will be processed.

The equal sign (=) is used to assign values ​​to variables. The operand to the left of the = operator is the name of the variable and the operand to the right of the = operator is the stored value.

assign multiple values ​​to multiple variables

You can assign multiple values ​​to multiple variables by separating the variables and values ​​with commas ( , ).

Example:


a, b = 100, 200
print(a)
print(b)

The output will be:


100
200

set more than three variables

You can set more than three variables. It is also possible to customize to different types.

Example:


a, b, c, d = 6, "string", 5.66, False
print(a)
print(b)
print(c)
print(d)

The output will be:


6
string
5.66
False

Set the variable as a tuple

If there is a single variable on the left side, it is set as a tuple.

Example:


a = 100, 200
print(a)
print(type(a))

The result will be:


(100, 200)
<class 'tuple'>

Note: We use the type function to get the type of a variable in Python. And how to write it like this: type(variableName)

The number of variables must be equal to the number of values.

If the number of variables on the left and the number of values ​​on the right do not match, we will get a ValueError.

 Example:


a, b = 100, 200, 300
 print(a)
 print(b)
 a, b, c = 100, 200
 print(a)
 print(b)
 print(c)

 We will get the following error:


a, b, c = 100, 200
ValueError: not enough values ​​to unpack (expected 3, got 2)


a, b = 100, 200, 300
 ValueError: too many values ​​to unpack (expected 2)

Assign unmatched or trailing variables as a list by appending an (*) to the variable name.

 Example:


*a, b = 100, 200, 300
 print(a)
 print(type(a))

 The result would be:


[100, 200]
<class 'list'>

 Assign the same value to multiple variables.

We can assign any number of variables with a single value.

 To assign multiple variables with a single value in a statement in Python, we use the following syntax.


variable_1 = variable_2 = variable_3 = value

 Example:


a = b = 100
 print(a)
 print(b)

 The output will be:


 100
 100

 Practical example:

 In the following program we take the variables for months and assign values ​​of 31 for months with 31 days, 30 for months with 30 days, and 28 for February. We allocate 31 days for all months in one statement. Likewise for months with 30 days.


jan = mar = may = jul = aug = oct = undefined dec = 31
 apr = jun = sep = nov = 30
 feb = 28
 total = jan + feb + mar + apr + may + jun + jul + aug + sep + oct + nov + dec
 print(total)

 The output will be:


 365

 more information

 You may wish to refer to the following resources for additional information on this topic

 Python documentation

 If you have any questions? Leave it in the comments



Tags


Python python variables

Share page