Python: using zip and cycle to iterate through multiple iterables

Hey, everyone!

Today we are going to talk about 2 very useful features to iterate through multiple series: zip and cycle

Let's say you have two or more iterables and you need to iterate through both of them. In this situation you can use zip to combine them. Zip returns an iterator object, pairing each member of each series. It accepts iterables of any type (lists, tuples, sets, strings). Here is how it works:

list1 = [1,2,3,4]
tuple2 = (4,3,2,1)

for a,b in zip(list1, tuple2):
   print(a,b)

>> 1 4
>> 2 3
>> 3 2
>> 4 1

If you have more than two lists, you can just add it to the zip too:

list1 = [1, 2, 3, 4]
list2 = [4, 3, 2, 1]
list3 = ['a', 'b', 'c', 'd']

for a,b,c in zip(list1, list2, list3):
   print(a,b,c)

>> 1 4 a
>> 2 3 b
>> 3 2 c
>> 4 1 d

If one of the lists has a different size, the elements are going to be paired up until the size of the smallest list:

list1 = [1,2,3,4,5,6,7,8]
list2 = [4,3,2,1,0,-1]
list4 = ['a','b','c']
for a,b,c in zip(list1, list2, list4):
    print(a,b,c)

>>1 4 a
>>2 3 b
>>3 2 c

We can use cycle from itertools to repeat the values of the smallest list:

from itertools import cycle

list1 = [1,2,3,4]
list2 = [4,3,2,1]
list4 = ['a','b','c']
for a,b,c in zip(list1, list2, cycle(list4)):
   print(a,b,c)

>>1 4 a
>>2 3 b
>>3 2 c
>>4 1 a

Something to have in mind: when using zip with unordered iterables (set, dicts) we have no guarantee of which order our elements are going to appear. For example:

list1 = [1,2,3,4]
set1 = {4,3,2,1}
for a,b in zip(set1, list1):
   print(a,b)

>>1 1
>>2 2
>>3 3
>>4 4

Now it is your turn!

Can you complete de following function using zip and cycle:

def make_dict(list_of_keys, list_of_values):
    #your implementation
    return d

d = make_dict([1, 2, 3, 4], ['a', 'b'])
print(d)
>> {1: 'b', 2: 'a', 3: 'b', 4: 'a'}