Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rewrite of zip function won't work

Tags:

python

I'm rewriting the zip function as a practice of my Python skills. The aim is to write it using list comprehension, although I am not 100% sure I am fully comfortable with it hence I'm doing this.

Here is what I have so far:

def zip(l1, l2):
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])

z = zip(['a', 'b', 'c'], [1,2,3])
for i in z: print(i)

And here is the error I am getting, which I am unsure of how to fix!

Traceback (most recent call last):
  File "path-omitted", line 47, in <module>
    z = zip(['a', 'b', 'c'], [1, 2,3])
  File "path-omitted", line 45, in zip
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
  File "path-omitted", line 45, in zip
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
  File "path-omitted", line 45, in zip
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
  File "path-omitted", line 45, in zip
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
IndexError: list index out of range
like image 442
madcrazydrumma Avatar asked Dec 24 '22 12:12

madcrazydrumma


1 Answers

Your zip function implementation is recursive. At some point l1[1:] or l2[1:] will become empty, and attempts to access the first element will fail with IndexError.

Check if both l1 and l2 are nonempty and return empty list if they are:

def zip(l1, l2):
    if not (l1 and l2):
        return []
    return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])

Or you could catch IndexError and return []:

def zip(l1, l2):
    try:
        return [(l1[0], l2[0])] + zip(l1[1:], l2[1:])
    except IndexError:
        return []
like image 167
vaultah Avatar answered Jan 09 '23 06:01

vaultah