user6402446
user6402446

Reputation: 57

Compare lists within a python to list to find common elements

consider a list of lists as given here.

many_lists = [[1,999,91,120,11], [909,800,7620,11], [1,101,800,7620]]

the output of this should be:

output_lst = [11, 1, 800, 7620]

I need to compare each list with the rest of the lists and if there is a common element then it should be in the output.

is there a simpler way to do this without two loops?

edit: (order within the output_list is not important)

Upvotes: 0

Views: 273

Answers (2)

Chandella07
Chandella07

Reputation: 2117

Without third loop, using set and intersaction:

many_lists = [[1,999,91,120,11], [909,800,7620,11], [1,101,800,7620]]

alist = []
for _ind, id in enumerate(many_lists):
    for j in many_lists[_ind+1:]:
        alist.append(list(set(id) & set(j)))
print(*alist)

Upvotes: 0

Mustafa Aydın
Mustafa Aydın

Reputation: 18306

One way is to run a counter over the flattened list and choose those that appeared more than once:

from collections import Counter
from itertools import chain

flattened = chain.from_iterable(many_lists)

result = [elem
          for elem, count in Counter(flattened).items()
          if count > 1]

to get

>>> result
[1, 11, 800, 7620]

Upvotes: 2

Related Questions