Skip to content
Advertisement

Creating a function that works like “zip”

I am trying to make a function that does something similar to “zip”. My problem is that the part

a = L4[l:len(L4):len(L)]

doesn’t work. In the case below, it should take every third element from the L4, and append it to a new list, so I ended up with [[1, 4, 7], [2, 5, 8], [3, 6, 9]], but that is not really what is happening. Also, it would be even better if I could make tuples, so it would look like [(1, 4, 7), (2, 5, 8), (3, 6, 9)], but I don’t know how to do that…

L = [[1,2,3], [4,5,6], [7,8,9]]
L4 = []
def my_zip(L):
    l = 0
    for i in L:
        if isinstance(i, list):
            my_zip(i)
        else:
            L4.append(i)
    while l < len(L):
        a = L4[l:len(L4):len(L)]
        l += 1
        L5.append(a)
    return L5
print(my_zip(L))

Advertisement

Answer

Try this one.

def zip_copy(*args):
    lst = []
    i = 0
    t = tuple()
    for a in range(len(min(args,key=len))):
        for a in args:
            t+=(a[i],)
        i+=1
        lst +=(t,)
        t = tuple()
    return lst 
print(zip_copy([1,2],[3,4],[3,5])) # [(1, 3, 3), (2, 4, 5)]
print(list(zip([1,2],[3,4],[3,5]))) # [(1, 3, 3), (2, 4, 5)]
# ------------------------------------#
print(zip_copy([1,2])) # [(1,), (2,)]
print(list(zip([1,2]))) # [(1,), (2,)]
# ------------------------------------ #
print(zip_copy("Hello","Hii")) # [('H', 'H'), ('e', 'i'), ('l', 'i')]
print(list(zip("Hello","Hii"))) # [('H', 'H'), ('e', 'i'), ('l', 'i')]
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement