Teaching Kids Programming: Videos on Data Structures and Algorithms
In Python, the zip and zip_longest are two commonly used functions to do a zipping operations on two lists or tuples. For how to use them, you can refer to: Python’s zip_longest Function and Beginner’s Guide to the zip() function in Python3.
Today, we are going to implement (re-invent) these two functions in Python.
zip function implementation in Python
The zip takes one element from both list/tuple at a time. It will stop at the less length. Therefore, we can implement a zip that returns an array.
def zip(a, b):
la = min(len(a), len(b))
ans = []
for i in range(la):
ans.append((a[i], b[i]))
return ans
Similar to the existing zip function in Python, we can convert it into a generator which yields one element at a time – instead of generating a entire list.
def zip(a, b):
la = min(len(a), len(b))
for i in range(la):
yield (a[i], b[i])
How to Implement a zip_longest in Python?
Similarly, we fulfill the empty elements by None for longest zipping:
Generating all zip_longest list.
def zip_longest(a, b):
la = max(len(a), len(b))
ans = []
for i in range(la):
aa = None if i >= len(a) else a[i]
bb = None if i >= len(b) else b[i]
ans.append((aa, bb))
return ans
Returning one element at a time via yield in the generator:
def zip_longest(a, b):
la = max(len(a), len(b))
for i in range(la):
aa = None if i >= len(a) else a[i]
bb = None if i >= len(b) else b[i]
yield (aa, bb)
–EOF (The Ultimate Computing & Technology Blog) —
428 wordsLast Post: Python's zip_longest Function
Next Post: Teaching Kids Programming - Re-implement the enumerate in Python using yield in a Generator