SoFunction
Updated on 2025-03-01

A detailed explanation of zip functions in Python

In Python, it is often necessary to traverse multiple sequences at the same time when processing data.zipFunctions provide a concise way to combine these sequences, which are used to pair elements of multiple iterable objects (such as lists, tuples, etc.) to create a new iterator whose elements are tuples composed of parallel elements in the input iterable object. This allows us to easily pair elements of multiple sequences.

First knowing zip

The zip function can accept any number of iterable objects as parameters.

zip(*iterables)

iterables: One or more iterable objects.

Basic usage

numbers = [1, 2, 3]
colors = ['red', 'blue', 'green']

zipped_pairs = zip(numbers, colors)

zipped_pairsIt is an iterator that containsnumbersandcolorsThe pairing of elements in the element can be done even if the numbers and colors types are different (a list, a ancestral).

<zip object at 0x7f9df0d9c190>

To see the specific content, you can convert it to a list.

list(zipped_pairs)

Output result:

[(1, 'red'), (2, 'blue'), (3', 'green')]

Decompress

The zip object supports decompression, and can be directlyforUsed in a loop to facilitate iteration.

for number, color in zip(numbers, colors):
    print(f"The number {number} is the color {color}")

Processing sequences of inequality

When tryingzipWhen the two iterable objects processed are sequences of varying lengths, shorter sequences limit the number of generated tuples.

short_numbers = [1, 2]
long_colors = ['red', 'blue', 'green', 'yellow']

zipped = zip(short_numbers, long_colors)
list(zipped)

Output result:

[(1, 'red'), (2, 'blue')]

Use itertools.zip_longest to handle sequences of inequality

For sequences of varying lengths, if you need to process to the end of the longest sequence, you can useitertools.zip_longest

import itertools

zipped_longest = itertools.zip_longest(short_numbers, long_colors)
list(zipped_longest)

Output result:

[(1, 'red'), (2, 'blue'), (None, 'green'), (None, 'yellow')]

itertools.zip_longestAllow you to specify afillvalueParameter, used to fill in missing values, defaultNone

Flexibility of zip function

zipFunctions are not only suitable for lists and tuples, but also handle any iterable objects, including strings, dictionaries, collections, etc.

Combined with * operator

zipand*Combining operators can quickly generate dictionaries.

keys = ['a', 'b', 'c']
values = [1, 2, 3]

my_dict = dict(zip(keys, values))
print(my_dict)

Output result:

{'a': 1, 'b': 2, 'c': 3}

This is the end of this article about a detailed explanation of zip functions in Python. For more related Python zip functions, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!