Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create my own zip() function in Python

as a personal exercise I am trying to create my own little zip() function that takes two lists and puts the items into a list of tuples. In other words if these are my list:

fr = [6,5,4]
tr = [7,8,9]

I would expect this:

[(6,7), (5,8), (4,9)]

Here is my code:

def zippy(x, y):
    zipper = []
    for i in x :
        for g in y:
            t = (i,g)
        zipper.append(t)

What I get is: [(6, 9), (5, 9), (4, 9)], but when I define the lists inside of the function, it works as intended. Any help is appreciated.

like image 458
SeaWolf Avatar asked Sep 13 '25 22:09

SeaWolf


1 Answers

Use indexes to access same-indexes items:

def zippy(x, y):
    zipper = []
    for i in range(len(x)):
        zipper.append((x[i], y[i]))
    return zipper

using list comprehension:

def zippy(x, y):
    return [(x[i], y[i]) for i in range(len(x))]

>>> fr = [6,5,4]
>>> tr = [7,8,9]
>>> zippy(fr, tr)
[(6, 7), (5, 8), (4, 9)]
like image 153
falsetru Avatar answered Sep 16 '25 11:09

falsetru