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.
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)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With