ᚱᛗ
© 2022
Powered by Hugo

Unpacking Iterables

Table of Contents

Overview

Any iterable object in Python can be unpacked, this includes: strings, lists, tuples, named tuples, bytes, arrays, etc. The only requirement is that the iterable yields exactly one item per variable assignment (unless you use a star * to capture excess items in a single container).

Unpacking n-element Tuple to n Variables

a, b, c = (100, 200, 300)
c1, c2, c3, c4 = "atom"
print(c1 + c2 + c3 +c4)  # "atom"

One-line Variable Swaping

a, b = ("black", "white")
a, b = b, a
print(a, b)  # white black

Prefixing an Argument Object with a Star

divmod(20, 4)  # returns (x//y, x%y) == (5, 0)
xy = (20, 4)
divmod(*xy)  # (5, 0)

Grabbing a Group of Items

# example container
materials = ["gold", "diamond", "copper", "silver"]
# from the left
*head, a, b = materials
print(f"{head}, {a}, {b}")  # ['gold', 'diamond'], copper, silver
*head, a, b, c, d = materials
print(f"{head}, {a}, {b}, {c}, {d}")  # [], gold, diamond, copper, silver
# from the middle
a, *middle, z = materials
print(f"{a}, {middle}, {z}")  # gold, ['diamond', 'copper'], silver
# from the right
a, b, *tail = materials
print(f"{a}, {b}, {tail}")  # gold, diamond, ['copper', 'silver']
a, b, c, *tail = materials
print(f"{a}, {b}, {c}, {tail}")  # gold, diamond, copper, ['silver']
a, b, c, d, *tail = materials
print(f"{a}, {b}, {c}, {d}, {tail}")  # gold, diamond, copper, silver, []

Nested Unpacking

metro_areas = [
    ("Tokyo", "JP", 36.933, (35.689722, 139.691667)),
    ("Delhi NCR", "IN", 21.935, (28.613889, 77.208889)),
    ("Mexico City", "MX", 20.142, (19.433333, -99.133333)),
    ("New York-Newark", "US", 20.104, (40.808611, -74.020386)),
    ("Sao Paulo", "BR", 19.649, (-23.547778, -46.635833)),
]

for row in metro_areas:
    # *data, coords = row  # short version if data is not of interest
    city, country, pop, coords = row
    print(f"latitude: {coords[0]}; longitude: {coords[1]}")

# latitude: 35.689722; longitude: 139.691667
# latitude: 28.613889; longitude: 77.208889
# latitude: 19.433333; longitude: -99.133333
# latitude: 40.808611; longitude: -74.020386
# latitude: -23.547778; longitude: -46.635833