English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Python basic tutorial

Python flow control

Fonctions en Python

Types de données en Python

Python file operations

Python objects and classes

Python date and time

Advanced Python knowledge

Python reference manual

Python zip() usage and examples

Python built-in functions

The zip() function accepts iterable items (can be zero or more), aggregates them into a tuple, and then returns it.

The syntax of the zip() function is:

zip(*iterables)

zip() parameters

ParametersDescription
iterablesIt can be an in-built iterable item (such as: list, string, dictionary) or a user-defined iterable item

Recommended reading: Python iterator, __iter__ and __next__

zip() return value

The zip() function returns an iterator of tuples based on the iterable object.

  • If no parameters are passed, zip() returns an empty iterator

  • If a single iterable is passed, zip() returns an iterator of tuples, each with only one element.

  • If multiple iterables are passed, zip() returns an iterator of tuples, each of which has elements from all iterables.
    Assuming two iterable variables are passed to zip(); one containing three elements and the other containing five elements. Then, the returned iterator will contain three tuples. This is because the iterator stops when the shortest iterable is exhausted.

Example1: Python zip()

number_list = [1, 2, 3]
str_list = ['one', 'two', 'three']
# No iterable parameter
result = zip()
# Convert an iterator to a list
result_list = list(result)
print(result_list)
# Two iterables
result = zip(number_list, str_list)
# Convert iterator to set
result_set = set(result)
print(result_set)

Output result

[]
{(2, 'two'), (3, 'three'), (1, 'one')}

Example2: Different numbers of iterable elements

numbersList = [1, 2, 3]
str_list = ['one', 'two']
numbers_tuple = ('ONE', 'TWO', 'THREE', 'FOUR')
# Note, the size of numbersList and numbers_tuple is different
result = zip(numbersList, numbers_tuple)
# Convert to set collection
result_set = set(result)
print(result_set)
result = zip(numbersList, str_list, numbers_tuple)
# Convert to set collection
result_set = set(result)
print(result_set)

Output result

{(2, 'TWO'), (3, 'THREE'), (1, 'ONE')}
{(2, 'two', 'TWO'), (1, 'one', 'ONE')}

Operators*can be used with zip() to unzip lists.

zip(*zippedList)

Example3: use zip() to unzip values

coordinate = ['x', 'y', 'z']
value = [3, 4, 5]
result = zip(coordinate, value)
result_list = list(result)
print(result_list)
c, v = zip(*result_list
print('c =', c)
print('v =', v)

Output result

[('x', 3), ('y', 4), ('z', 5)]
c = ('x', 'y', 'z')
v = (3, 4, 5)

Python built-in functions