7 Levels of Using the Zip Function in Python

0
(0)

Programming skills are a quality that distinguishes one candidate from another during an interview. That’s why we pay close attention to this question. The elegance of constructions and the conciseness and succinctness of code demonstrate a programmer’s skill and experience.

On 365educating articles, we’ve already covered numerous examples of how to improve your Python code, how to work with strings in Python, reviewed basic library functions, and much more. Today, we’ll dedicate an entire article to a lesser-known but very useful function: zip.

A functionzip is a function in Python that combines elements from different iterables, such as lists, tuples, or sets, and returns an iterator.

This feature can make code very elegant. However, its use is not very intuitive for beginners and sometimes leads to errors.

For example, we have a matrix 2*3represented by a nested list:

matrix = [[1, 2, 3], [1, 2, 3]]

Here’s a popular Python interview question:

How to get the transpose of the above matrix?

A Junior developer might write several for loops to implement it, but a Senior developer only needs one line of code:

matrix_T = [list(i) for I in zip(*matrix)]

Elegant, isn’t it?

If you haven’t figured out the solution above yet, don’t worry. This article will explain the concepts and usage of this powerful function in detail zip. If you’re already familiar with this approach but want to learn more amazing tricks with the function zip, this article is for you.

Level 0: Basics of using the zip function

The function zipCombines elements from different iterables, such as lists, tuples, or sets, and returns an iterator.

For example, we can use it to concatenate two lists like this:

id = [1, 2, 3, 4]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']

record = zip(id, leaders)

print(record)

# zip object at 0x7f266a707d80

print(list(record))
# [(1, 'Elon Mask'), (2, 'Tim Cook'), (3, 'Bill Gates'), (4, 'Yang Zhou')]

As shown in the example above, the function zipreturns an iterator of tuples, where the i-th tuple contains the i-th element of each of the lists.

It looks like the zipper on your jacket works, doesn’t it?

Level 1: Connecting fewer or more elements

In fact, zipPython’s zipper function is much more powerful than a physical zipper. It can operate on any number of iterables simultaneously, not just two.

If we pass a single list to the zip function:

id = [1, 2, 3, 4]
record = zip(id)
print(list(record))
# [(1,), (2,), (3,), (4,)]

How about three lists?

id = [1, 2, 3, 4]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']
sex = ['male', 'male', 'male', 'male']

record = zip(id, leaders, sex)

print(list(record))

# [(1, 'Elon Mask', 'male'), (2, 'Tim Cook', 'male'), (3, 'Bill Gates', 'male'), (4, 'Yang Zhou', 'male')]

As stated above, no matter how many iterable objects we pass to the function zip, it works as expected.

By the way, if there is no argument, the zip function simply returns an empty iterator.

Level 2: Working with Arguments of Unequal Lengths

Real data isn’t always clean and complete; sometimes we have to process iterables of unequal length. By default, the function’s result zipdepends on the shortest object.

id = [1, 2]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']

record = zip(id, leaders)

print(list(record))

# [(1, 'Elon Mask'), (2, 'Tim Cook')]

As shown in the code above, idis the shortest list, so recordit contains only two tuples, and the last two leaders in the list leadershave been skipped.

What if the last two leaders are unhappy about being ignored? Python can help us again. The module itertoolscontains another function, zip_longest. As the name suggests, it’s a sibling of zip, and its result depends on the longest argument.

Let’s use zip_longest to create a list of records:

from itertools import zip_longest
id = [1, 2]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']

long_record = zip_longest(id, leaders)
print(list(long_record))
# [(1, 'Elon Mask'), (2, 'Tim Cook'), (None, 'Bill Gates'), (None, 'Yang Zhou')]

long_record_2 = zip_longest(id, leaders, fillvalue='Top')
print(list(long_record_2))
# [(1, 'Elon Mask'), (2, 'Tim Cook'), ('Top', 'Bill Gates'), ('Top', 'Yang Zhou')]

Now neither Bill Gates nor Yang Zhou will be upset. The optional argument fillvaluecan help us fill in the missing values. The argument’s default value is None, But we can put anything we want there! It’s still unclear what would be more frustrating: not being included in the list recordor getting something like that next to our name. 

Level 3: Unpacking Operation

In the previous example, if we first get a list record, how can we unzip it into individual objects?

Unfortunately, Python doesn’t have an unzip function. However, if you’re familiar with asterisk tricks, unzipping is a very simple task.

record = [(1, 'Elon Mask'), (2, 'Tim Cook'), (3, 'Bill Gates'), (4, 'Yang Zhou')]
id, leaders = zip(*record)
print(id)
# (1, 2, 3, 4)
print(leaders)
# ('Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou')

In the example above, asterisk performed the unpacking operation on all four tuples from the list record.

If we don’t use the asterisk method, the following method will be identical:

record = [(1, 'Elon Mask'), (2, 'Tim Cook'), (3, 'Bill Gates'), (4, 'Yang Zhou')]

print(*record)
# unpack the list by one asterisk

# (1, 'Elon Mask') (2, 'Tim Cook') (3, 'Bill Gates') (4, 'Yang Zhou')

id, leaders = zip((1, ‘Elon Mask’), (2, ‘Tim Cook’), (3, ‘Bill Gates’), (4, ‘Yang Zhou’))
print(id)

# (1, 2, 3, 4)
print(leaders)
# ('Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou')

Level 4: Creating and Updating Dictionaries with the zip Function

This function zipmakes it very easy to create or update dictionaries based on individual lists. There are two one-line solutions:

  • Use dict comprehensionandzip
  • Using the function dictandzip
id = [1, 2, 3, 4]
leaders = ['Elon Mask', 'Tim Cook', 'Bill Gates', 'Yang Zhou']

# create dict by dict comprehension
leader_dict = {i: name for i, name in zip(id, leaders)}
print(leader_dict)
# {1: 'Elon Mask', 2: 'Tim Cook', 3: 'Bill Gates', 4: 'Yang Zhou'}

# create dict by dict function
leader_dict_2 = dict(zip(id, leaders))
print(leader_dict_2)
# {1: 'Elon Mask', 2: 'Tim Cook', 3: 'Bill Gates', 4: 'Yang Zhou'}

# update
other_id = [5, 6]
other_leaders = ['Larry Page', 'Sergey Brin']
leader_dict.update(zip(other_id, other_leaders))
print(leader_dict)
# {1: 'Elon Mask', 2: 'Tim Cook', 3: 'Bill Gates', 4: 'Yang Zhou', 5: 'Larry Page', 6: 'Sergey Brin'}

The example above doesn’t use for loops at all. How elegant!

Level 5: Using the zip Function in For Loops

This is a common scenario when multiple iterables are being processed concurrently.

Let us illustrate this with the following example:

products = ["cherry", "strawberry", "banana"]
price = [2.5, 3, 5]
cost = [1, 1.5, 2]
for prod, p, c in zip(products, price, cost):
print(f'The profit of a box of {prod} is £{p-c}!')
# The profit of a box of cherry is £1.5!
# The profit of a box of strawberry is £1.5!
# The profit of a box of banana is £3!

Is there a neater way to implement the example above? Hardly.

Level 6: Matrix Transpose

Finally, we return to the Python interview question:

How to get the transpose of a matrix?

Since we are already familiar with the function zip, unpacking with a single asterisk, and dict comprehensionThe one-line solution becomes intuitive:

matrix = [[1, 2, 3], [1, 2, 3]]
matrix_T = [list(i) for i in zip(*matrix)]
print(matrix_T)
# [[1, 1], [2, 2], [3, 3]]

Conclusion

The function zipis very useful and powerful in Python. Using it correctly can help us write less code and perform more operations.

It’s not for nothing that “Do more with less” is the Python philosophy.

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

As you found this post useful...

Follow us on social media!

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?


Explore More IT Terms


Share this term: Facebook X LinkedIn WhatsApp Email

Leave a Reply

Your email address will not be published. Required fields are marked *