Skip to content Skip to sidebar Skip to footer

Pairwise Appending In Python Without Zip

I am currently learning list comprehension in Python. How would I do the following: l1 = [2,4,6,8] l2 = [2,3,4,5] l = [*some list comprehension*] so that l = [[2,2],[4,3],[6,4],[8

Solution 1:

You want the zip function.

Example -

>>>l1 = [2,4,6,8]>>>l2 = [2,3,4,5]>>>>>>l = list(zip(l1,l2))>>>l
[(2, 2), (4, 3), (6, 4), (8, 5)]

If you want the inner lists to be of type list instead of tuple -

>>> l = [list(x) for x in zip(l1,l2)]
>>> l
[[2, 2], [4, 3], [6, 4], [8, 5]]

In python 3.x, zip returns an iterator, so if you do not want a list, but just want to iterate over each combined (zipped) element, you can just directly use - zip(l1,l2) .

As it is asked in the question, to do it without zip function, you can use enumerate function to get the index as well as the element from one list and then use the index to get the element from second list.

>>> l = [[x,l2[i]]for i,x in enumerate(l1)]
>>> l
[[2, 2], [4, 3], [6, 4], [8, 5]]

But this would not work unless both lists have same size.Also not sure why you would want to do it without zip .

Solution 2:

Using list comprehension and zip:

>>>l1 = [2, 4, 6, 8]>>>l2 = [2, 3, 4, 5]>>>[[x, y] for x, y inzip(l1, l2)]
[[2, 2], [4, 3], [6, 4], [8, 5]]

Solution 3:

You can use zip as

>>>l1 = [2,4,6,8]>>>l2 = [2,3,4,5]>>>zip(l1,l2)
[(2, 2), (4, 3), (6, 4), (8, 5)]
>>>[ list(x) for x inzip(l1,l2) ]
[[2, 2], [4, 3], [6, 4], [8, 5]]

Post a Comment for "Pairwise Appending In Python Without Zip"