0

After collecting values, list_3 is created for example:

list_1 = ['a','b','c','d']
list_2 = ['e','f','g','h']
list_3 = [list_1,list_2]

I would like to print the results in this model text sequence:

a and e
b and f
c and g
d and h

I tried to use it as follows:

for i, event in enumerate(list_3):
    print(list_3[i][i] + ' ' + list_3[i+1][i])

But it returned in error:

    print(list_3[i][i] + ' ' + list_3[i+1][i])
IndexError: list index out of range

What is the correct way to proceed to recover the corresponding prints?

Digital Farmer
  • 1,705
  • 5
  • 17
  • 67

2 Answers2

2

Use zip() to traverse multiple lists in parallel:

for x, y in zip(*list_3)):
    print(f"{x} and {y}")
Barmar
  • 741,623
  • 53
  • 500
  • 612
1

Instead of enumerate, use zip. zip allows you to iterate over the two lists together:

for i,j in zip(list_1, list_2):
    print(i + ' and ' + j)

Output:

a and e
b and f
c and g
d and h