Python Zip: Seamlessly Compress Your Way to Efficiency

Python Zip: Seamlessly Compress Your Way to Efficiency

According to the Python documentation:


zip(*iterables)
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.


Let’s see an example:


# zip.grades.py
>>> grades = [18, 23, 30, 27]
>>> avgs = [22, 21, 29, 24]
>>> list(zip(avgs, grades))
[(22, 18), (21, 23), (29, 30), (24, 27)]
>>> list(map(lambda *a: a, avgs, grades))
[(22, 18), (21, 23), (29, 30), (24, 27)]y        

Here, we’re zipping together the average and the grade for the last exam for each student. Notice how easy it is to reproduce zip() using map() (the last two instructions of the example). Here as well, in order to visualize the results, we have to use list().


A simple example of the combined use of map() and zip() could be a way of calculating the element-wise maximum among sequences; that is, the maximum of the first element of each sequence, then the maximum of the second one, and so on:



# maxims.py
>>> a = [5, 9, 2, 4, 7]
>>> b = [3, 7, 1, 9, 2]
>>> c = [6, 8, 0, 5, 3]
>>> maxs = map(lambda n: max(*n), zip(a, b, c))
>>> list(maxs)
[6, 9, 2, 9, 7]y        


Notice how easy it is to calculate the maximum values of three sequences. zip() is not strictly needed of course — we could just use map(). Sometimes it’s hard, when showing a simple example, to grasp why using a technique might be good or bad. We forget that we aren’t always in control of the source code; we might have to use a third-party library that we can’t change the way we want. Having different ways to work with data is therefore really helpful.


That’s it for today. See you tomorrow.


Zain Ali

Software Engineer | Backend Developer?? | GoLang Expert?

1 年

of course...python is most powerful language across all fields of programming

要查看或添加评论,请登录

Usama Sarwar的更多文章

社区洞察

其他会员也浏览了