Home > Net >  How to iterate over two lists in a specific order
How to iterate over two lists in a specific order

Time:12-10

I have two lists:

list1 = ['A','C','E','G','A']
list2 = ['B','D','F','H','N']

I would like to create these new names and append them to an empty list

A_vs_B
C_vs_D
E_vs_F
G_vs_H
A_vs_N

The structure is, the 1st item in list1 with 1st item in list 2 and so on. I only want these names.

This is what I've done so far

newlist = []
for i in list1:
    for j in list 2:
        name = i   '_vs_'   j
        newlist.append(name)

The problem with this it creates every possible combination of names between list1 & list2. How do I limit my loop to only produce names I want?

CodePudding user response:

use zip(), which takes two lists (or other iterables) and creates an iterable of tuples. In the for loop unpack the tuple to the variables i and j

newlist = []
for i, j in zip(list1, list2):
    name = i   '_vs_'   j
    newlist.append(name)

You could further improve your code using format-strings:

newlist = []
for i, j in zip(list1, list2):
    newlist.append(f'{i}_vs_{j}')

and using list-comprehensions:

newlist = [f'{i}_vs_{j}' for i, j in zip(list1, list2)]

CodePudding user response:

You could try:

list1 = ['A','C','E','G','A']
list2 = ['B','D','F','H','N']

newlist = []

for i in range(0, len(list1)):
    name = list1[i]   '_vs_'   list2[i]
    newlist.append(name)
print(newlist)
  • Related