I have an arbitrary list of lists, for example
x = [
[5, 1, 2, 3, 4],
[5, 6, 7, 8, 9],
[5, 10, 11, 12]
]
There is only one element which is a member of all three lists in x = 5
My question: What is the most pythonic method of testing membership of elements in an arbitrary number of lists?
My solution is as follows, but feels like it could be simpler:
y = x[0]
if len(x) > 1:
for subset in x[1:]:
x = list(set(x) & set(subset))
EDIT: The output should be a list with the common elements included.
For the example above, it would be [5]
If the example above had two elements (e.g. 5 and foo) the output should be [5, "foo"]
You can use
functools.reduceto solve this problem: