tuple unpacking
Assigning the items of a tuple or other sequence to several names at once, as in x, y = point.
In more detail
The number of names must match the number of items, or Python raises ValueError. The reverse, writing a, b on the right, packs values into a tuple, so a, b = b, a swaps two variables. It works in a for heading too: for name, colour in pairs:.
Example
for name, age in [("Ana", 30), ("Bo", 25)]:
print(name, age)Related terms
- tuple — An ordered, fixed-length group of values in which each position can have its own meaning and type.
- assignment — A statement with a single equals sign, name = expression, which evaluates the right side and makes the name on the left refer to the result.
- for loop — A loop that runs its body once for each item in a list or other collection, setting a loop variable to the current item.
Taught in
- Loops And Tuples — Hands-on Python: Complete Video Course & Book
- Graphical Applications With While — Hands-on Python: Complete Video Course & Book
- Chapter Three In One Sitting — Hands-on Python: Complete Video Course & Book
- Tuples, And The Comma That Makes Them — PCEP Certified Entry-Level Python Programmer (PCEP-30-02) Exam Prep