Using for loops when iterating through 2 lists that have different lengths can be error-prone, especially when the lengths of these lists can change with time.
Let us see an example to see when that happens:
This example actually works well, but if we were to change the length of the *first_list*, let’s say we want to increase its length, then we are going to end up with errors:
This is going to throw the following error:
IndexError: list index out of range
This happens because the first list has more elements than the second list and since we are using the first list’s length as an upper bound to how much we are increasing the index, we are going to get to the index 3 (the index of the first element is 0, the index of the second element is 1, and so on) and there is no element in the second list that has an index of 3.
To help us in such scenarios, we can simply use zip, which is going to be flexible even when the lengths of lists are not the same:
That’s it for this tutorial.
I hope you find this useful.