[Tips]How to access each n-th item of lists

Though the following is one of the ways to access items of multiple list, an error “index out of range” will occur when the lengths of the lists are different. How can I solve it?

list1 = ["A", "B", "C", "D"]
list2 = [1, 2, 3, 4]
list3 = ["Apple", "Orange", "Banana", "Peach"]

for i in range(len(list1)):
    print(list1[i], list2[i], list3[i])

The output is as below.

A 1 Apple
B 2 Orange
C 3 Banana
D 4 Peach

GOAL

To access each n-th item of multiple lists in one for loop.

Environment

Python 3.8.7

Method

Use zip() function.

for i1, i2, i3 in zip(list1, list2, list3):
    print(i1, i2, i3)

The zip() function returns an iterator of tuples combining items from each list.

list(zip(list1, list2, list3))
# => [('A', 1, 'Apple'), ('B', 2, 'Orange'), ('C', 3, 'Banana'), ('D', 4, 'Peach')]

The number of the tuples is the same as the length of the shortest list.

zip() should only be used with unequal length inputs when you don’t care about trailing, unmatched values from the longer iterables. If those values are important, useitertools.zip_longest() instead.

from https://docs.python.org/3/library/functions.html
from itertools import zip_longest
list1 = ["A", "B", "C", "D"]
list2 = [1, 2, 3, 4]
list3 = ["Apple", "Orange"]
for i1, i2, i3 in zip_longest(list1, list2, list3, fillvalue="??"):
    print(i1, i2, i3)

The output is as below.

A 1 Apple
B 2 Orange
C 3 ??
D 4 ??