Python Zip

Zip is a Python built-in function to iterate over multiple iterables in parallel.

Zip

zip is a Python built-in function to iterate over multiple iterables in a single statement. This provides a convenient way to perform parallel iteration over two or more sequences.

Take for example two separate lists of first names and last names. Assume the list of items are in the same corresponding order — hypothetically, say, a database stores records for all users with separate column fields for first name and last name. Looping through a zip of the two lists makes it easy to pair the first and last name together.

Loading...

Achieving the same output indexing into multiple lists using enumerate looks messy comparatively.

for idx, first_name in enumerate(first_names):
	last_name = last_names[idx]
	print(f'{first_name} {last_name}')

The zip function returns a zip object. Technically, the zip object is an iterator of tuples, which yields a tuple on each iteration. The first iteration of a zip object pairs together the values at index 0 from each iterable. The second iteration iteration combines the values at index 1, and so on.

A zip object can be converted into a list of tuples to demonstrate how the items within the iterables are joined.

result = zip(first_names, last_names)
print(list(result))

# Output:
# [('Tony', 'Soprano'), ('Carmela', 'Soprano'), ('Christopher', 'Moltisanti'),
#  ('Paulie', 'Gualtieri'), ('Silvio', 'Dante')]

However, beware of the edge case when the length of the iterables are uneven. zip will truncate the result to the shortest iterable ignoring additional items from longer iterables.

last_names.append('Melfi')
result = zip(first_names, last_names)
print(list(result))

# Output:
# [('Tony', 'Soprano'), ('Carmela', 'Soprano'), ('Christopher', 'Moltisanti'),
#  ('Paulie', 'Gualtieri'), ('Silvio', 'Dante')]

In this scenario, zip longest from the itertools module is a suitable alternative to fill in the missing values.

Loading...
Published