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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
I am an experienced and passionate Senior Software Engineer with a demonstrated history of working in the full life cycle of software development with enormous curiosity for data science, machine learning, algorithms, data structures, and solving challenging problems. I am an open-source enthusiast at https://github.com/fatosmorina and also a writer.
I am open for new opportunities.