Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to iterate over two lists in a specific order

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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?

>Solution :

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)]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading