ScanSkill

zip

This zip() function returns a list of tuples, where the n-th tuple contains the n-th element from each of the argument sequences or iterables.

Syntax

zip([iterable, ...])

Here,

  • iterable: Optional. Must be a sequence, an iterator, or some other object which supports iteration.

Note: When there are multiple arguments that are all of the same lengths, zip() is similar to map() with an initial argument of None. With a single sequence argument, it returns a list of 1-tuples. With no arguments, it returns an empty list.

Examples

  • With the same no. of iterable elements
>>> # No iterable are passed
>>> zip()
[]

>>> # Two iterable are passed
>>> zip('hello', 'world')
[('h', 'w'), ('e', 'o'), ('l', 'r'), ('l', 'l'), ('o', 'd') ]
>>> zip((1, 1), (2, 4))
[(1, 2), (1, 4)]
>>> zip((1, 2), (3, 4))
[(1, 3), (2, 4)]
>>> zip([1, 2], [3, 4])
[(1, 3), (2, 4)]
  • With different no. of iterable elements
>>> zip((1, 2, 3), (4, 5))
[(1, 4), (2, 5)]
>>> zip((1, 2), (3, 4), (5, 6))
[(1, 3, 5), (2, 4, 6)]
  • With * operator to unzip a list
>>> # zip() in conjunction with the * operator can be used to unzip a list
>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True