0

I have 4 lists:

l1 = ['one', 'two', 'three']
l2 = ['one', 'six', 'three']
l3 = ['one', 'four', 'five']
l4 = ['one', 'three','five']

in order to find common intersection of all four lists I would do:

inter = set(l1).intersection(l2).intersection(l3).intersection(l4)

:return: {'one'}

How can I achieve the same with n number of lists in a list?

list_of_lists = [l1, l2, l3, l4]

Thank you in advance.

1 Answers1

3

Use a list of sets:

check_list = list(set(l) for l in (l2, l3, l4))

Then loop:

result = set(l1)
for s in check_list:
    result = result.intersection(s)
print(result)

Other option is to use reduce:

check_list = list(set(l) for l in (l1, l2, l3, l4))
from functools import reduce
result = reduce(set.intersection, check_list)

Here you have the live example

Netwave
  • 40,134
  • 6
  • 50
  • 93