Python: Built-in Function zip

>>> help(zip)

class zip(object)
 |  zip(*iterables) --> zip object
 |
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
 |

Example

>>> names = ['Apple', 'Brad', 'Cindy', 'Dante']
>>> ages = [30, 42, 25]

>>> type(zip(names, ages))
<class 'zip'>

>>> list(zip(names, ages))
[('Apple', 30), ('Brad', 42), ('Cindy', 25)]

>>> list(zip(names, ages, range(3)))
[('Apple', 30, 0), ('Brad', 42, 1), ('Cindy', 25, 2)]

>>> dict(zip(names, ages))
{'John': 28, 'Kevin': 19, 'Bob': 49}

>>> dict(zip(names, ages, range(3)))
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: dictionary update sequence element #0 has length 3; 2 is required

When using zip with set, the sequence may not be correct.

>>> color_set = {'R', 'G', 'B'}
>>> level_set = {1, 2, 3}

>>> list(zip(color_set, level_set))
[('B', 1), ('G', 2), ('R', 3)]

Empty zip object

>>> zip()
<zip object at 0x1040113c0>

>>> list(zip())
[]

>>> next(zip())
 Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
 StopIteration

For Python 2, use izip as zip to behave like zip in Python 3

try:
    from itertools import izip as zip
except ImportError:
    pass

Unzip or unpack iterables with with unpack operator * to pass in multiple arguments to zip function

  • a single asterisk (*) to unpack iterables (list, tuples, string etc.)
    • in function argument *args to pass in varying number of positional arguments
  • a double asterisk (**) to unpack dictionary
    • in function argument **kwargs to pass in varying number of keyword arguments
>>> pairs = [('John', 28), ('Kevin', 19), ('Bob', 49)]
>>> names, ages = zip(*pairs)

>>> list(zip(*pairs))
[('John', 'Kevin', 'Bob'), (28, 19, 49)]
>>> pairs = [('John', 28), ('Kevin', 19), ('Bob', 49)]

>>> def unpack(*args): print(f'args: {args}, len(args): {len(args)}')

>>> unpack(pairs)
args: ([('John', 28), ('Kevin', 19), ('Bob', 49)],), len(args): 1

>>> unpack(*pairs)
args: (('John', 28), ('Kevin', 19), ('Bob', 49)), len(args): 3

>>> list(zip(('John', 28), ('Kevin', 19), ('Bob', 49)))
[('John', 'Kevin', 'Bob'), (28, 19, 49)]

>>> zipped = zip(('John', 28), ('Kevin', 19), ('Bob', 49))
<zip object at 0x104011960>

>>> list(zipped)
[('John', 'Kevin', 'Bob'), (28, 19, 49)]

>>> names, ages = zip(('John', 28), ('Kevin', 19), ('Bob', 49))
>>> names
('John', 'Kevin', 'Bob')
>>> ages
(28, 19, 49)

>>> names, ages = zip(*pairs)
>>> names
('John', 'Kevin', 'Bob')
>>> ages
(28, 19, 49)


>>> head, *tail = pairs
>>> head
('John', 28)
>>> tail
[('Kevin', 19), ('Bob', 49)]

>>> [*names, *ages]
['John', 'Kevin', 'Bob', 28, 19, 49]

>>> (*names, *ages)
('John', 'Kevin', 'Bob', 28, 19, 49)

>>> {*names, *ages}
{'John', 'Bob', 49, 19, 28, 'Kevin'}

>>> [*'string']
['s', 't', 'r', 'i', 'n', 'g']
>>> age_lookup = dict(zip(names, ages))
>>> age_lookup
{'John': 28, 'Kevin': 19, 'Bob': 49}

>>> age_lookup['John'] = 30
>>> age_lookup
{'John': 30, 'Kevin': 19, 'Bob': 49}

>>> age_lookup.update({'John': 40})
>>> age_lookup
{'John': 40, 'Kevin': 19, 'Bob': 49}

>>> age_lookup.update(John = 50)
>>> age_lookup
{'John': 50, 'Kevin': 19, 'Bob': 49}

>>> age_lookup.update(zip(['John'], [60]))
>>> age_lookup
{'John': 60, 'Kevin': 19, 'Bob': 49}

>>> {**age_lookup, 'April': 21}
{'John': 60, 'Kevin': 19, 'Bob': 49, 'April': 21}

zip in JavaScript

$ node

> letters = ['a', 'b']
> numbers = [1, 2, 3, 4]

> Array.from({length: 2})
[ undefined, undefined ]

> Array.from({length: Math.min(letters.length, numbers.length)})
[ undefined, undefined ]

> Array.from({length: Math.min(letters.length, numbers.length)}).map((_, i) => [letters[i], numbers[i]])
[ [ 'a', 1 ], [ 'b', 2 ] ]

> zip = (a, b) => Array.from({length: Math.min(letters.length, numbers.length)}).map((_, i) => [a[i], b[i]])

> zip(letters, numbers)
[ [ 'a', 1 ], [ 'b', 2 ] ]

> zip(numbers, letters)
[ [ 1, 'a' ], [ 2, 'b' ] ]

Leave a Comment

Your email address will not be published.

nineteen − 6 =