Teaching Kids Programming – Introduction and Re-implement the zip and zip_longest Function in Python


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.

1
2
3
4
5
6
def zip(a, b):
    la = min(len(a), len(b))
    ans = []
    for i in range(la):
        ans.append((a[i], b[i]))
    return ans
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.

1
2
3
4
def zip(a, b):
    la = min(len(a), len(b))
    for i in range(la):
        yield (a[i], b[i])
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.

1
2
3
4
5
6
7
8
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
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:

1
2
3
4
5
6
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)
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) —

GD Star Rating
loading...
445 words
Last Post: Python's zip_longest Function
Next Post: Teaching Kids Programming - Re-implement the enumerate in Python using yield in a Generator

The Permanent URL is: Teaching Kids Programming – Introduction and Re-implement the zip and zip_longest Function in Python

Leave a Reply