Parallel Traversals with zip function

The range() function allows us to traverse sequences with for in a non-exhaustive fashion. The zip() function allows us to use for loops to visit multiple sequences in parallel (during the same loop).

The zip() takes one or more sequences as arguments and returns a series of tuples that pair up parallel items taken from those sequences.

Suppose we’re working with two lists:

L1 = ['honda', 'yamaha', 'suzuki']
L2 = [3000, 2500, 2000]

print(zip(L1, L2))

The terminal output will be:

ddn_ro@Linux:~$ python3 test.py
<zip object at 0x7f0a0da2dbc8>

To combine the items in L1 and L2, we can use zip to create a list of tuple pairs.

L1 = ['honda', 'yamaha', 'suzuki']
L2 = [3000, 2500, 2000]

print(zip(L1, L2))

L3 = list(zip(L1, L2))
print(L3)

The terminal output will be:

ddn_ro@Linux:~$ python3 test.py
<zip object at 0x7f0a0da2dbc8>
[('honda', 3000), ('yamaha', 2500), ('suzuki', 2000)]

When wedded with the for loop, it supports parallel iterations.

L1 = ['honda', 'yamaha', 'suzuki']
L2 = [3000, 2500, 2000]

print(zip(L1, L2))

L3 = list(zip(L1, L2))
print(L3)

for (b, p) in zip(L1, L2):
	print(b, ' costs ', p)

The terminal output will be:

ddn_ro@Linux:~$ python3 test.py
<zip object at 0x7f0a0da2dbc8>
[('honda', 3000), ('yamaha', 2500), ('suzuki', 2000)]
honda  costs  3000
yamaha  costs  2500
suzuki  costs  2000

The zip() function accepts any type of sequence (any iterable object, including files), and it accepts more than two arguments. With three arguments, it builds a list of three-item tuples with items from each sequence.

T1 = ('honda', 'yamaha', 'suzuki')
T2 = (3000, 2500, 2000)
T3 = ('red', 'blue', 'white')

L3 = list(zip(T1, T2, T3))
print(L3)

The terminal output will be:

ddn_ro@Linux:~$ python3 test.py
[('honda', 3000, 'red'), ('yamaha', 2500, 'blue'), ('suzuki', 2000, 'white')]

Leave a Reply