Inline Assignment in Python

In Python, you can assign multiple values to multiple variables simultaneously using a single assignment statement.

var1, var2 = value1, value2

or

var1, var2 = (value1, value2)

A Practical Example

Example 1

I have a tuple that contains the x, y, z coordinates of a 3D Cartesian diagram.

To assign each value of the tuple to a different variable, I can write:

  1. data = (1, 2, 3)
  2. x, y, z = data
  3. print(x, y, z)

This script assigns each value from the tuple to the variable in sequence.

The output of the program is:

1
2
3

Example 2

In this script, I use inline assignment to assign three values to three variables.

  1. x, y, z = 1, 2, 3
  2. print(x, y, z)

This script assigns the values to the variables following the order of assignment.

The output of the program is:

1
2
3

And so on.

 
 

Please feel free to point out any errors or typos, or share suggestions to improve these notes. English isn't my first language, so if you notice any mistakes, let me know, and I'll be sure to fix them.

FacebookTwitterLinkedinLinkedin
knowledge base

Variables in Python

  1. Variables
  2. Variable Types
  3. Strings
  4. Inline Assignment
  5. Lists
  6. Tuples
  7. Sets
  8. Dictionaries