Iterating over two lists at the same time accesses corresponding elements from the lists in parallel.
Solution for How to iterate over two lists at the same time in Python : You can use zip() and a for-loop to iterate over two lists Call zip(iter1 iter2) to create an iterator that aggregates corresponding elements from lists iter1 and iter2 together. Use a for-loop to iterate over this iterator, stopping at the length of the shorter list.
- This solution uses itertools.zip_longest(iter1, iter2) to iterate over two lists at the same time, stopping at the length of the longest list.
- This solution avoids an edge case where iter1 and iter2 are not the same size.
- Further reading: See documentation for zip_longest.