PythonPython Variables and Data TypesPython variables
What is multiple assignment in Python?
Question 38 of 88 · Updated
On this page
- 1. Assigning different values to multiple names
- 2. Swapping two variables without a temporary variable
- 3. Chained assignment: assigning the same object to several targets
- 4. Comparison of multiple-assignment forms
- 5. Extended iterable unpacking with a starred target
- 6. Nested unpacking
- 7. Right-hand evaluation order and target assignment order
- 8. Unpacking consumes iterators
- 9. Unpacking errors and partial assignment
- 10. Practical example: processing records with unpacking
- 11. Common mistakes and best practices
- Frequently asked questions
- Does multiple assignment work only with tuples?
- Is a = b = [] equivalent to a, b = [], []?
- Does Python use a temporary variable internally when swapping?
- Can a starred target collect zero elements?
- Does unpacking change the original object's elements?
- Interview-ready answer
- Official references
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#
PYTHONname, age = 'Asha', 21 print(name, age)
Output:
Asha 21The 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#
PYTHONa, b = 10, 20 a, b = b, a print(a, b)
Output:
20 10The 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.
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.
PYTHONa = b = [] a.append(1) print(b, a is b)
Output:
[1] TrueBoth names refer to one list. The append operation through a is visible through b.
To initialize two independent lists, evaluate two separate list displays:
PYTHONa, b = [], [] a.append(1) print(a, b, a is b)
Output:
[1] [] FalseThe 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#
| Form | Meaning |
|---|---|
| a, b = 1, 2 | Assign distinct corresponding values |
| a = b = 1 | Bind both names to the same result |
| a, b = b, a | Swap the original bindings |
| first, *rest = iterable | Bind one element and collect remaining elements in a list |
| a, (b, c) = nested | Recursively 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.
PYTHONfirst, *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.
PYTHONname, (x, y) = ('Asha', (3, 4)) print(name, x, y)
Output:
Asha 3 4The 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.
PYTHONdef observed(value): print('evaluate', value) return value x, y = observed(1), observed(2) print(x, y)
Output:
evaluate 1
evaluate 2
1 2Both 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.
PYTHONvalues = [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.
PYTHONdef 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.
| Expression | Exception | Reason |
|---|---|---|
| a, b = [1] | ValueError | Too few elements |
| a, b = [1, 2, 3] | ValueError | Too many elements |
| a, b = 42 | TypeError | The integer is not iterable |
| a, *b, *c = [1, 2, 3] | SyntaxError | Multiple 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.
PYTHONa = 0 try: a, (b, c) = 1, (2,) except ValueError: print(a)
Output:
1The 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#
PYTHONrecords = [('pen', 3, 20), ('book', 2, 50)] for name, quantity, price in records: print(name, quantity * price)
Output:
pen 60
book 100Each 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#
- Python Language Reference — Assignment statements
- Python Language Reference — Evaluation order
- Python Language Reference — Expression lists
- Python Tutorial — Tuples and sequences
- PEP 3132 — Extended Iterable Unpacking
- Python Language Reference — Data model
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.
References
- 1.Python Language Reference — Assignment statementsdocs.python.org
- 2.Python Language Reference — Evaluation orderdocs.python.org
- 3.Python Tutorial — Tuples and sequencesdocs.python.org
- 4.PEP 3132 — Extended Iterable Unpackingpeps.python.org
- 5.Python Language Reference — Data modeldocs.python.org
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design