This tutorial covers the following topic – Python Zip. It describes the syntax of the zip() function in Python. Also, it explains how the zip works and how to use it with the help of examples.

The zip() function allows a variable number of arguments (0 or more), but all iterables. The data types like Python liststringtupledictionary, set, etc. are all of the iterable types.

It groups the corresponding elements of all input iterables to form tuples, consolidates, and returns as a single iterable. Let’s check out about the Python zip function in more detail.

Zip() Function Explained with Examples

What is zip in Python?

The zip() is a built-in Python function. It is used to create an iterator of tuples (known as zip object) from a list of iterables passed as arguments.

Each tuple in the iterator contains elements that exist at a similar index in all the input iterables.

The size of the zip object depends on the shortest of the iterables passed to the Python zip function.

Python zip() syntax

''' Syntax(1) '''
 zip(iterator_1, iterator_2, iterator_3 ...)

Alternatively, the following syntax can also be referred:

''' Syntax(2) '''
 zip(*iterables)

Zip() parameters

The zip() function allows:

Python iterables or collections such as a list, string, dictionary, set, or any custom iterables.

Zip() return value

The zip() function returns a consolidated iterator that contains tuples holding adjacent values from input containers.

READ – Python Iterator

  • In case of zero no. of arguments, zip() returns a zero-sized iterator.
  • When only one iterable is passed, zip() still returns an iterator holding tuples with a single cardinal value. It means that every tuple will have one element.
  • In the case of multiple iterable arguments, the values at a similar index are grouped to form a tuple, and this process continues N times. N is the length of the shortest of iterables in the zip() parameters.

#python zip #python #programming

Zip Function in Python Explained with Examples
1.40 GEEK