Find similar values in a list of lists

Question:

I know this question is asked a lot, but they are all used for different things.
What I want to happen:

#python 3.9
list = [["grass", "sand", "water"],["rock", "grass", "sand"]]
matches = ["sand", "water"]

Is there a way to find matches this way?

Asked By: LeWolfYT

||

Answers:

Convert the lists into sets and take their intersection. You can do this across an arbitrarily long list of sets in a single line with functools.reduce:

>>> my_list = [["grass", "sand", "water"],["rock", "grass", "sand"]]
>>> import functools
>>> functools.reduce(set.intersection, map(set, my_list))
{'grass', 'sand'}
Answered By: Samwise
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.