Skip to content
Advertisement

Implemeting Zip(*iterables) using a For loop

I am trying to implement the zip(*iterables) function using a for loop and I am unable to do it. As you know, the zip function gets the first element of every list that’s passed into it, puts it in a tuple, then does the same with the second list of the elements in the list… and so on. In my case, I have been only able to do it with the first element.

This is as far as I got:

def inputlist(input_list):
    returned_list = []
    for i in input_list:
        for j in range(len(i)):
            returned_list.append(i[j])
            break

    return returned_list

FYI: This is purely for academic purposes and we are doing this just for the fun of it.

As an example, here’s the list that I am passing: [[2,3,4], [5,6,7], [8,9,10]]

Advertisement

Answer

Here is a zip implementation w/o zip().

For simplicity I did not handle the case of which the zip is bailing out when the number of elements is not in the same length. The pitfalls in your original code were the break that actually canceled one of the loops and the fact that you should have append the outer element ‘j’ with the inner value.

lst = [[1,2,3],[4,5,6]]

def inputlist(lst):
    inner_len = len(lst[0]) #in szip it isactually the minimum length of all the items
    returned_list = [[] for _ in range(inner_len)]
    for i in lst:
        for j in range(len(i)):
            returned_list[j].append(i[j])

    return returned_list

print(inputlist(lst))  # --> [[1, 4], [2, 5], [3, 6]]
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement