PythonPython Variables and Data TypesPython variables

What is multiple assignment in Python?

Question 38 of 88 · Updated

On this page

Multiple assignment lets you assign values to more than one target in a single Python statement. It commonly takes the form of iterable unpacking, such as a, b = 10, 20, or chained assignment, such as a = b = 0. These two forms are convenient but have different semantics.

Python evaluates the right-hand side before assigning to the targets. In unpacking, the values are assigned to the corresponding targets from left to right. In chained assignment, the same resulting object is assigned to each target.

1. Assigning different values to multiple names#

PYTHON
name, age = 'Asha', 21 print(name, age)

Output:

Asha 21

The comma-separated expressions on the right form a tuple value in the language's expression semantics. The target list on the left unpacks its two elements and binds them to name and age, respectively.

Parentheses are optional in this example. The comma, not parentheses alone, creates a tuple in ordinary tuple-display syntax.

The source does not have to be a tuple. A list, range, generator or other suitable iterable can be unpacked. Without a starred target, the number of elements must match the number of targets at the corresponding nesting level.

2. Swapping two variables without a temporary variable#

PYTHON
a, b = 10, 20 a, b = b, a print(a, b)

Output:

20 10

The expression on the right uses the original values of b and a before either target is assigned. This allows the two names to exchange their bindings without an explicitly named temporary variable.

Loading diagram…

The diagram describes language-level evaluation order, not a guarantee about the interpreter's internal stack or tuple allocation. Python implementations may optimize simple assignments while preserving observable semantics.

For two ordinary local names, this operation uses a constant number of references and assignments, irrespective of the sizes of the objects those names refer to. It swaps references rather than copying the underlying objects. The statement is not a general synchronization mechanism for concurrent shared state.

A common incorrect alternative is a = b followed by b = a. After the first statement, the original binding of a has been lost unless it was retained elsewhere.

3. Chained assignment: assigning the same object to several targets#

The syntax a = b = expression evaluates expression once and assigns the resulting object to the targets in order.

When the value is immutable, this is often convenient for initialization. With mutable values, it can introduce unintended sharing.

PYTHON
a = b = [] a.append(1) print(b, a is b)

Output:

[1] True

Both names refer to one list. The append operation through a is visible through b.

To initialize two independent lists, evaluate two separate list displays:

PYTHON
a, b = [], [] a.append(1) print(a, b, a is b)

Output:

[1] [] False
Loading diagram…

The diagrams show the relationship immediately after initialization, before append is called. Chained assignment is not a copying operation. Ordinary name assignment binds the target to the resulting object.

4. Comparison of multiple-assignment forms#

FormMeaning
a, b = 1, 2Assign distinct corresponding values
a = b = 1Bind both names to the same result
a, b = b, aSwap the original bindings
first, *rest = iterableBind one element and collect remaining elements in a list
a, (b, c) = nestedRecursively unpack a nested structure

These are assignment statements, not equality comparisons. They are also different from passing unpacked arguments to a function, which uses related syntax in a different grammatical context.

5. Extended iterable unpacking with a starred target#

A single starred target within a target list collects remaining items into a new list.

PYTHON
first, *middle, last = range(5) print(first, middle, last) print(type(middle).__name__) a, *rest = [1] print(a, rest)

Output:

0 [1, 2, 3] 4
list
1 []

The first example assigns the first item to first, the final item to last, and the intervening items to middle. The starred result is a list even when the source is a range or tuple.

The second example shows that the starred list can be empty. The input still needs enough elements for all non-starred targets.

There can be at most one starred target in a given target list. Nested target lists may have their own starred targets. The starred target does not recursively copy its elements; its list contains references to the collected objects.

For a finite iterable of n elements, extended unpacking ordinarily requires O(n) iteration work and O(n) auxiliary reference storage in the worst case, excluding the iterable's internal cost. A starred target can consume an entire iterator, so avoid using this pattern on unbounded iterables or unexpectedly large streams.

6. Nested unpacking#

Multiple assignment can express the expected structure of nested data directly.

PYTHON
name, (x, y) = ('Asha', (3, 4)) print(name, x, y)

Output:

Asha 3 4

The outer target list expects two items. The second item is itself unpacked into two targets. Each level must satisfy its own unpacking requirements.

Nested unpacking is useful for structured results and records with a stable shape. If the data comes from an external source with uncertain structure, validate it before relying on a deeply nested target pattern.

7. Right-hand evaluation order and target assignment order#

Right-hand expressions are evaluated before the target assignments begin. Their evaluation follows Python's expression evaluation order.

PYTHON
def observed(value): print('evaluate', value) return value x, y = observed(1), observed(2) print(x, y)

Output:

evaluate 1
evaluate 2
1 2

Both function calls take place before the names are assigned their new values.

Assignments to targets then proceed left to right. This matters when a target depends on a name assigned earlier in the same statement.

PYTHON
values = [0, 0] i = 0 i, values[i] = 1, 9 print(i, values)

Output:

1 [0, 9]

First, i becomes 1. The second target uses that updated index, so values[1] becomes 9. The result is not [9, 0].

For simple name swaps, the idiom is clear and safe. For overlapping targets, attributes or indexed collections, separate statements may better communicate the intended order.

8. Unpacking consumes iterators#

Unpacking an iterator advances it to obtain the required values.

PYTHON
def numbers(): yield 4 yield 5 source = numbers() x, y = source print(x, y, list(source))

Output:

4 5 []

The generator has been consumed by unpacking. Calling list on the same generator afterward produces an empty list.

Do not assume that an iterator can be traversed repeatedly like a list. If the source produces too many values for an unstarred target list, unpacking raises ValueError and may already have advanced the iterator.

9. Unpacking errors and partial assignment#

The following expressions demonstrate common failures. Run them independently because an uncaught error stops normal execution.

ExpressionExceptionReason
a, b = [1]ValueErrorToo few elements
a, b = [1, 2, 3]ValueErrorToo many elements
a, b = 42TypeErrorThe integer is not iterable
a, *b, *c = [1, 2, 3]SyntaxErrorMultiple starred targets at the same level

All four exception types were confirmed locally.

An assignment statement is not a transaction. A failure during nested unpacking or target assignment does not necessarily undo earlier assignments.

PYTHON
a = 0 try: a, (b, c) = 1, (2,) except ValueError: print(a)

Output:

1

The outer unpacking succeeds and a is assigned 1. The inner unpacking fails because it expects two items but receives one. The earlier assignment remains visible.

If atomic state changes are required, validate and compute the proposed changes first, then commit them using a suitable application-level mechanism.

10. Practical example: processing records with unpacking#

PYTHON
records = [('pen', 3, 20), ('book', 2, 50)] for name, quantity, price in records: print(name, quantity * price)

Output:

pen 60
book 100

Each record is unpacked into descriptive names. This is often clearer than repeatedly indexing a tuple by position. The loop expects each record to provide exactly three values.

For n fixed-width records, this performs O(n) unpacking and arithmetic operations under conventional fixed-size numeric cost assumptions. It uses constant auxiliary local storage excluding the input, printed output and object-specific processing costs.

For real order processing, define a validated record schema and explicit currency and rounding rules. Do not treat this demonstration as a complete billing implementation.

11. Common mistakes and best practices#

  • Do not confuse chained assignment with independent initialization of mutable objects.
  • Use a, b = b, a for ordinary variable swapping rather than arithmetic or XOR-based tricks.
  • Check the expected number of elements before unpacking uncertain external data.
  • Remember that a starred target creates a list and can consume a finite iterator completely.
  • Keep unpacking targets short and descriptive. Overlapping targets can make evaluation order surprising.
  • Do not assume that failed nested assignments roll back earlier bindings.
  • Use named records, dataclasses or other structured representations when positional fields become difficult to maintain.

Frequently asked questions#

Does multiple assignment work only with tuples?#

No. Iterable unpacking works with compatible iterables such as lists, ranges and generators. The iterable must provide the number of elements required by the target pattern.

Is a = b = [] equivalent to a, b = [], []?#

No. The first statement binds two names to one list. The second evaluates two list displays, creating two separate lists.

Does Python use a temporary variable internally when swapping?#

No explicit temporary variable is required in source code. Python evaluates the original right-hand values before assigning the targets. Internal allocation and bytecode details depend on the implementation and version.

Can a starred target collect zero elements?#

Yes. It receives an empty list if the input contains exactly enough elements for the other targets.

Does unpacking change the original object's elements?#

Unpacking itself binds or assigns the extracted references. It does not inherently copy or mutate the original collection, although consuming an iterator advances it and custom iteration or assignment methods can have side effects.

Interview-ready answer#

Multiple assignment allows Python to assign to several targets within one statement. For example, a, b = 10, 20 unpacks two corresponding values, while a = b = 0 assigns the same resulting object to both names. The right-hand expressions are evaluated before the targets are assigned, so a, b = b, a swaps two ordinary variables without an explicitly named temporary variable. Python also supports nested and starred iterable unpacking. The main pitfalls are mismatched element counts, unintended sharing of mutable objects and the left-to-right order of target assignment.

Official references#

Verification note: Eleven runnable examples were executed in independent namespaces on Python 3.13.5, and all documented outputs matched. Four additional exception tests passed. The two Mermaid flowcharts use standard fenced syntax and were manually reviewed for evaluation order, reference sharing and label accuracy. No local Mermaid parser or CLI was available. Official reference links are supplied under the authorized offline research exception; live documentation, Supabase changelog and public-site rendering were not checked.

Related questions

Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design