24. Multiple Assignment in Python

In Python, multiple assignment allows you to assign values to multiple variables in a single line of code.
This makes your code shorter, cleaner, and easier to read.
Python supports assigning different values to multiple variables simultaneously, assigning the same value to several variables at once, and extracting elements directly from collections (unpacking).
# Assigning multiple values in a single line
name, age, score = "Alex", 14, 95.5

print(name)   # Output: Alex
print(age)    # Output: 14
print(score)  # Output: 95.5

24.1. Assigning Multiple Values to Multiple Variables

You can assign multiple values to multiple variables at the same time by separating both variable names and values with commas:

  • Positional Mapping: Values on the right side of the = operator are assigned to variables on the left side in exact positional order.

  • Atomic Evaluation: Python evaluates all expressions on the right-hand side first before making any assignments.

  • Swapping Variables: This feature makes swapping the values of two variables effortless without needing a temporary variable!

# Positional assignment
x, y, z = 10, 20, 30

# Swapping variables in one line
a = 5
b = 90
a, b = b, a  # Now a is 90 and b is 5!

24.1.1. Quiz: Multiple Values Assignment

24.1.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
a
a
b = b
commas
match
right
right

1. In positional multiple assignment, Python assigns values from left to Drop here.
2. Python evaluates all expressions on the Drop here side of the `=` sign before assigning values.
3. You can swap two variables `a` and `b` in one line using the syntax Drop here.
4. Multiple variable names on the left side of an assignment must be separated by Drop here.
5. The number of variables on the left must Drop here the number of values on the right when assigning multiple values.

24.1.1.2. Code Ordering Examples

Example 1: Assign three values to three variables in one line and print the second variable.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(y)
☰
x, y, z = 5, 10, 15

Example 2: Swap the values of two variables first and second in a single line.

Drag and drop lines into the correct order and click to adjust indentation:
☰
first = "Apple"
☰
second = "Banana"
☰
print(first)
☰
first, second = second, first

Example 3: Assign two calculated mathematical expressions to two variables simultaneously.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(area)
☰
width, height = 5 + 5, 10 * 2
☰
area = width * height

24.1.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What are the values of a and b after running a, b = 1, 2?

Correct! Python assigns values positionally from left to right.

Incorrect. Values match corresponding variable positions.

Incorrect. Each variable gets its corresponding positional value.

Incorrect. Two variables match two values cleanly.

How do you swap the values of two variables x and y in standard Python?

Correct! Python evaluates the right side first and assigns both values simultaneously.

Incorrect. This sets x to y, losing x’s original value before y updates.

Incorrect. swap() is not a built-in Python function.

Incorrect. == is a comparison check, not an assignment statement.

What happens if you run x, y = 10, 20, 30 in Python?

Correct! Variable count (2) does not match value count (3).

Incorrect. Python requires exact count matching.

Incorrect. Mismatched counts raise an exception.

Incorrect. Variables are not auto-created.

What output is produced by p, q = 3, 4; p, q = q, p + 2; print(p, q)?

Correct! Right side evaluates to (4, 3 + 2) which is (4, 5) before assigning to p and q.

Incorrect. p was 3 during right-side evaluation.

Incorrect. Reassignment updates both variables.

Incorrect. p receives q’s initial value (4).

Which character is used to separate variables during multiple assignment?

Correct! Commas separate target variables and source expressions.

Incorrect. Semicolons separate distinct lines of statements.

Incorrect. Colons mark block header endings.

) | Incorrect. Pipes are bitwise or logical union operators.

Why is atomic evaluation important in a, b = b, a + b?

Correct! Atomic evaluation prevents partial state corruption during assignment.

Incorrect. Atomic evaluation ensures logic correctness rather than execution speed.

Incorrect. Values retain their exact data types.

Incorrect. It controls order of evaluation during assignment.

What is the result of m, n = 10, 20; m, n = m * 2, n / 2; print(m, n)?

Correct! m becomes 10 * 2 = 20; n becomes 20 / 2 = 10.0 (float division).

Incorrect. Standard division / always returns a float type in Python 3.

Incorrect. Reassignment updates both values.

Incorrect. Counts match correctly.

Given a, b, c = 1, 2, 3, what does print(c) output?

Correct! c corresponds to the third position on the right-hand side.

Incorrect. 1 is assigned to variable a.

Incorrect. 2 is assigned to variable b.

Incorrect. Positional assignment sets individual scalar values.

What error is raised by a, b, c = 5, 10?

Correct! 3 variables were provided but only 2 values were given.

Incorrect. Missing values trigger ValueError during unpacking.

Incorrect. No index operations were called.

Incorrect. Syntax structure is valid, but runtime value count mismatches.

What will x, y = 10 + 2, 5 * 2 leave inside x and y?

Correct! Right-hand expressions evaluate to 12 and 10 before positional assignment.

Incorrect. Mathematical expressions are evaluated first.

Incorrect. 5 * 2 evaluates to 10.

Incorrect. Expressions inside multiple assignments are completely valid.

Question 1 of 0

24.2. Assigning One Value to Multiple Variables

When you want several variables to store the exact same initial value, you can chain assignment operators (=):

  • Chained Assignment: Uses multiple = signs in a single statement (e.g., a = b = c = 0).

  • Shared Value: All variables are assigned the exact same value or object reference.

  • Common Uses: Ideal for initializing multiple counter variables, scores, or flags to zero or default states.

# Chained assignment
score1 = score2 = score3 = 0

print(score1)  # Output: 0
print(score2)  # Output: 0
print(score3)  # Output: 0

24.2.1. Quiz: Chained Assignment

24.2.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
5
chained
initialize
not
right

1. Setting multiple variables to the same value in one line using multiple `=` signs is called Drop here assignment.
2. In `a = b = c = 5`, variable `b` receives the value Drop here.
3. Chained assignment statements are evaluated from Drop here to left.
4. Chained assignment is commonly used to Drop here counter or score variables at the start of a program.
5. Modifying a primitive integer variable `a` after `a = b = 10` does Drop here change variable `b`.

24.2.1.2. Code Ordering Examples

Example 1: Initialize three score variables to zero in a single chained assignment line.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(player1)
☰
player1 = player2 = player3 = 0

Example 2: Assign the string “Active” to two status variables and print one.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(status2)
☰
status1 = status2 = "Active"

Example 3: Initialize two variables to 100, update one, and display both.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(x, y)
☰
x = x + 50
☰
x = y = 100

24.2.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

What is the value of variable x after running x = y = z = 50?

Correct! All three variables receive the rightmost value 50.

Incorrect. The rightmost value 50 is assigned.

Incorrect. Chained assignment does not add values together.

Incorrect. All variables cleanly hold integer 50.

Which statement correctly initializes a, b, and c to the number 10?

Correct! Chained assignment syntax assigns 10 to all targets.

Incorrect. Raises ValueError because 3 variables require 3 values or an iterable.

Incorrect. == tests equality rather than performing variable assignment.

Incorrect. Comma assignment requires proper tuple/value structures.

Given p = q = 5; p = 10, what are the values of p and q?

Correct! Reassigning primitive variable p does not alter q.

Incorrect. Primitive reassignments do not affect other variables.

Incorrect. p was explicitly reassigned to 10.

Incorrect. p received 10, q remained 5.

In which direction does Python process chained assignment statements (like a = b = 5)?

Correct! 5 is evaluated first, then assigned to b, and then assigned to a.

Incorrect. Rightmost expressions evaluate first in chained assignments.

Incorrect. Evaluation occurs within a single line right-to-left.

Incorrect. Python evaluation order is strictly defined.

Why do programmers use chained assignment?

Correct! It removes repetitive assignment lines.

Incorrect. Loops require for or while statements.

Incorrect. Variables remain fully reassignable.

Incorrect. Module importing uses import keywords.

What does a = b = c = "Hello" output when running print(b)?

Correct! Variable b received string “Hello”.

Incorrect. “Hello” is assigned as data content.

Incorrect. b holds “Hello”.

Incorrect. Valid string chained assignment.

Given x = y = 20; y = y + 5, what does print(x) yield?

Correct! x remains 20 because updating y does not alter x.

Incorrect. Modifying y leaves x untouched.

Incorrect. x was initialized to 20.

Incorrect. Both variables were defined cleanly.

What is output by a = b = c = 2 * 4; print(a)?

Correct! Expression 2 * 4 evaluates to 8 first, assigning 8 to c, b, and a.

Incorrect. Mathematical expression evaluates fully first.

Incorrect. Expression result is 8.

Incorrect. Multiplication yields 8.

Which of the following is TRUE regarding primitive variables assigned via x = y = 100?

Correct! Modifying one primitive variable later will not change the other.

Incorrect. Integers are immutable primitives.

Incorrect. Both remain standard reassignable variables.

Incorrect. Both can be printed normally.

What will v1 = v2 = v3 = True; print(v1 and v2) evaluate to?

Correct! Both v1 and v2 hold Boolean True, so True and True evaluates to True.

Incorrect. Both variables hold True.

Incorrect. Boolean logical check yields True.

Incorrect. Valid Boolean chained assignment.

Question 1 of 0

24.3. Sequence and Collection Unpacking

Extracting individual elements from a collection (like a list, tuple, or string) directly into variables is called unpacking:

  • List & Tuple Unpacking: Elements inside a list or tuple are automatically extracted into variables from left to right.

  • String Unpacking: Individual characters of a string can be unpacked into separate variables.

  • Exact Match Requirement: The number of variables on the left must strictly equal the number of items in the collection.

# Unpacking a list
point = [100, 200]
x_coord, y_coord = point

# Unpacking a string
char1, char2, char3 = "CAT"

print(x_coord)  # Output: 100
print(char2)    # Output: A

24.3.1. Quiz: Sequence Unpacking

24.3.1.1. Fill-in-the-Blanks (Cloze)

Complete the following sentences by filling in the blanks.
Word Bank (Drag items below):
3
ValueError
character
positional
unpacking

1. Extracting values from a list or tuple into individual variables is called Drop here.
2. Unpacking a string like `"PYTHON"` into individual variables yields one Drop here per variable.
3. Unpacking a 3-element list requires exactly Drop here receiving variables.
4. If the variable count does not match the collection length, Python raises a Drop here.
5. Elements in list unpacking are assigned in Drop here order from index 0 upwards.

24.3.1.2. Code Ordering Examples

Example 1: Unpack a list containing RGB color values into three variables.

Drag and drop lines into the correct order and click to adjust indentation:
☰
rgb_colors = [255, 128, 0]
☰
print(red)
☰
red, green, blue = rgb_colors

Example 2: Unpack a 3-letter string into three separate character variables.

Drag and drop lines into the correct order and click to adjust indentation:
☰
print(letter2)
☰
word = "DOG"
☰
letter1, letter2, letter3 = word

Example 3: Unpack a nested tuple of dimensions and compute volume.

Drag and drop lines into the correct order and click to adjust indentation:
☰
dimensions = (2, 5, 10)
☰
print(volume)
☰
length, width, height = dimensions
☰
volume = length * width * height

24.3.1.3. Multiple Choice Questions

Progress: 0
Score: 0 / 0
Question 1 of 0

Given data = [10, 20, 30]; x, y, z = data, what value is assigned to y?

Correct! y receives the second item from list data (index 1).

Incorrect. 10 is assigned to x.

Incorrect. 30 is assigned to z.

Incorrect. Unpacking extracts individual values.

What happens if you run a, b = [1, 2, 3] in Python?

Correct! Cannot unpack a 3-item list into only 2 variables.

Incorrect. Strict count matching is required.

Incorrect. Requires explicit extended unpacking syntax.

Incorrect. Mismatched unpacking length raises ValueError.

What is assigned to b when unpacking string a, b, c = "SKY"?

Correct! Strings are iterables; the second character “K” maps to b.

Incorrect. “S” is assigned to variable a.

Incorrect. “Y” is assigned to variable c.

Incorrect. Unpacking distributes single characters.

Which Python data structure can be unpacked into variables?

Correct! Python supports unpacking on all iterable objects.

Incorrect. Integers are non-iterable scalar values.

Incorrect. Booleans cannot be iterated or unpacked.

Incorrect. Floats are scalar objects.

Given pairs = (4, 8); num1, num2 = pairs, what does print(num1 + num2) output?

Correct! num1 receives 4 and num2 receives 8; 4 + 8 = 12.

Incorrect. Unpacked items are numeric integers, so addition occurs.

Incorrect. Values are extracted from tuple pairs.

Incorrect. Addition of integers is valid.

What error occurs if you try to unpack a non-iterable object like x, y = 100?

Correct! Integers are not iterables and cannot be unpacked.

Incorrect. Non-iterables fail type checks first.

Incorrect. Identifier syntax is valid.

Incorrect. No list indexing took place.

If coords = [5, 10], which statement successfully extracts both values?

Correct! Unpacks both items into variables x and y.

Incorrect. Invalid syntax bracket usage.

Incorrect. Assigns the whole list reference to both variables.

Incorrect. Tries to assign unassigned variables x and y into coords.

What is output by items = ["book", "pen"]; item1, item2 = items; print(item1)?

Correct! item1 gets the first list element “book”.

Incorrect. “pen” is assigned to item2.

Incorrect. Unpacking extracts individual scalar elements.

Incorrect. Valid list unpacking syntax.

Given a, b, c = [7, 7, 7], what is print(a == b == c)?

Correct! All three variables hold value 7, making equality test True.

Incorrect. All values equal 7.

Incorrect. Equality check yields Boolean True.

Incorrect. Counts match perfectly.

Why is unpacking considered a Pythonic practice?

Correct! Unpacking eliminates verbose indexing syntax.

Incorrect. Scope rules apply equally.

Incorrect. Unpacking affects code syntax in memory.

Incorrect. Console output requires print().

Question 1 of 0