How do I compare two lists of pairs to see which pair combinations exist in both?

Question:

Here is a simple example of what I am trying to do. So with two lists of pairs, such as:

pairs1 = [(egg,dog),(apple,banana),(orange,chocolate),(elephant,gargoyle),(cat,lizard)]
pairs2 = [(cat,lizard),(ice,hamster),(elephant,giraffe),(apple,gargoyle),(dog,egg)]

I want to be able to retrieve the pair combinations that the two lists have in common. So for these two lists, the pairs retrieved would be (cat,lizard) and (dog,egg). The order of the elements within in the pair don’t matter, just the fact that the pair combination is within the same tuple.

Asked By: BanAckerman

||

Answers:

Try:

pairs1 = [
    ("egg", "dog"),
    ("apple", "banana"),
    ("orange", "chocolate"),
    ("elephant", "gargoyle"),
    ("cat", "lizard"),
]
pairs2 = [
    ("cat", "lizard"),
    ("ice", "hamster"),
    ("elephant", "giraffe"),
    ("apple", "gargoyle"),
    ("dog", "egg"),
]

x = set(map(frozenset, pairs1)).intersection(map(frozenset, pairs2))
print(list(map(tuple, x)))

Prints:

[('lizard', 'cat'), ('egg', 'dog')]
Answered By: Andrej Kesely