How Do You Iterate Through Two Lists of Unequal Length in Python?

Problem scenario
You want to iterate through two lists and perform some operation. The lists are not equal length. You want to iterate through them in some type of step-by-step fashion despite their lack of equality. What should you do?

Solution
Use this as an example:

list_a = [1, 2, 3]
list_b = ["dog", "cat", "rat", "chicken"]

i = 0
j = 0

while (i < len(list_a)) or (j < len(list_b)):
    if (i < len(list_a)):
        print(list_a[i])
        i += 1
    if (j < len(list_b)):
        print(list_b[j])
        j += 1

Leave a comment

Your email address will not be published. Required fields are marked *