When using Python to work with data, it is not uncommon to have the data separated in multiple sources.
So a very common initial task is to load each source of data and then combine them using some code like the one below.
The zip()
and enumerate()
functions are primarily used with for
loops.
Combining both of them together gives you the power to iterate as many iterables as you need and also get an index for each item simultaneously.
In the code snippet below, the enumerate()
function will attach an index to each item in the loop while the zip()
function will merge the iterables together by pairing the items from each list.
cars = ['F8','X5','GT']
brands = ['Ferrari','BMW','McLaren']
colors =['Red','Blue','Black']
for index, (car,brand,color) in enumerate(zip(cars, brands, colors)):
print(f'{index} -> {brand} : {car} : {color}')
The output for the code above is:
0 -> Ferrari : F8 : Red
1 -> BMW : X5 : Blue
2 -> McLaren : GT : Black