Home > OS >  Comparing the 1st element of list of lists to another list then adding only the lists that match to
Comparing the 1st element of list of lists to another list then adding only the lists that match to

Time:01-19

My aim is to compare the 1st element of a list of lists with another list and have the lists added to a new list if the 1st elements of both lists match. So for instance,

list1 = [2,4,7,10]
list2 = [[2,5],[3,7],[1,6],[10,3]]

newlist = [[2,5],[10,3]]

CodePudding user response:

I would use a list comprehension:

[snd for fst, snd in zip(list1, list2) if fst == snd[0]]

This outputs:

[[2, 5], [10, 3]]

CodePudding user response:

You can use zip():

newlist = []

for a, b in zip(list1, list2):
    if a == b[1]:
        newlist.append(b)

Or with a generator expression:

newlist = [b for a, b in zip(list1, list2) if a == b[1]]
  • Related