Skip to content

`enumerate`, `zip`, and iterable unpacking [ref]

Problem

  • Pair ["a", "b"] with indices starting at 0 and at 1.
  • Zip [1, 2, 3] with [4, 5] and observe where iteration stops.
  • Transpose ["abc", "def"] using zip and argument unpacking.
  • Unpack and sum each pair in [(1, 2), (3, 4)].

Python solution

list(enumerate(["a", "b"]))          # [(0, 'a'), (1, 'b')]
list(enumerate(["a", "b"], start=1))  # [(1, 'a'), (2, 'b')]

list(zip([1, 2, 3], [4, 5]))  # [(1, 4), (2, 5)]

list(zip(*["abc", "def"]))
# [('a', 'd'), ('b', 'e'), ('c', 'f')]

sums = []
for a, b in [(1, 2), (3, 4)]:
    sums.append(a + b)
sums  # [3, 7]