Ivan Leung
Ivan Leung

Reputation: 11

How to compare one list to multiple lists in python to see if there are any matching?

New to python programming. I am trying to compare a with l1 to l6 and see if there are any matching

I think I should use some type of loop to do but struggling to figure out how to move from one list to another in the loop.

Any direction would be great!

Example list -

l1 = [14, 19, 34, 39, 59, 11]
l2 = [6, 13, 34, 46, 62, 1]
l3 = [18, 34, 44, 60, 69, 22]
l4 = [46, 54, 57, 58, 66, 10]
l5 = [27, 32, 50, 52, 57, 12]
l6 = [11, 44, 45, 46, 70, 25]

a = [11, 44, 45, 46, 70, 25]

Upvotes: 1

Views: 581

Answers (2)

Lennart G.
Lennart G.

Reputation: 11

The easiest way is to place all your lists in a list of lists and iterate through that list. You actually have two options here:

The first would be to create one 2-dimensional list containing all your lists:

lists = [
    [14, 19, 34, 39, 59, 11],
    [6, 13, 34, 46, 62, 1],
    [18, 34, 44, 60, 69, 22],
    [46, 54, 57, 58, 66, 10],
    [27, 32, 50, 52, 57, 12],
    [11, 44, 45, 46, 70, 25]
]

The second option would be to create a list containing the references to your created list:

lists = [l1,l2,l3,l4,l5,l6]

Regardless of the option you choose, you can then iterate through your list and compare your lists with a for loop like this:

for list in lists:
    if list == a:
        return list

Upvotes: 1

RazaChishti
RazaChishti

Reputation: 33

hope this will help just converting the lists in to set and using intersection to find common ones

l1 = [14, 19, 34, 39, 59, 11]
l2 = [6, 13, 34, 46, 62, 1]
l3 = [18, 34, 44, 60, 69, 22]
# convert lists into sets
l1 = set(l1) 
l2 = set(l2) 
l3 = set(l3)
# intersection of sets 
set1 = a.intersection(l2) 
set2 = a.intersection(l1)
result_set_new = set2.intersection(set1) 
result_set = result_set_new.intersection(l3) 
final_list = list(result_set) 
print(final_list) 

Upvotes: 0

Related Questions