Python - Function zip


Suppose we're working with two lists:

L1 = [1,2,3,4] 
L2 = [5,6,7,8] 

To combine the items in these lists, we can use zip to create a list of tuple pairs.

Like range, zip is a list in Python 2.X, but an iterable object in 3.X.

L1 = [1,2,3,4] 
L2 = [5,6,7,8] 

print( zip(L1, L2) )
print( list(zip(L1, L2)) )                      # list() required in 3.X, not 2.X 

for (x, y) in zip(L1, L2): 
     print(x, y, '--', x+y) 

Here, we step over the result of the zip call.

The pairs of items pulled from the two lists.

This for loop uses the tuple assignment form we met earlier to unpack each tuple in the zip result.

Related Topics