0

I would like to collect all the items that exist in every sublist. Let's say the list of lists looks like this:

list[0] = ['A', 'B', 'C', 'D']
list[1] = ['X', 'B', 'A']
list[2] = ['R', 'C', 'A', 'B', 'X']

'A' and 'B' exist in every sublist and my goal is to save these to another list:

list2 = ['A', 'B']

I've been trying to use list comprehension but I can't figure out how to get it to work the way I want. Any help is greatly appreciated!

Fred_Alb
  • 174
  • 11

3 Answers3

1

Use set intersections, and then convert the result back to a list.

your_list = [
    ['A', 'B', 'C', 'D'],
    ['X', 'B', 'A'],
    ['R', 'C', 'A', 'B', 'X']
]

print(set.intersection(*map(set,your_list)))

If you know the values per list are unique in the first place, and you don't care about order, then you can just use a list of sets in your original code, so this simplifies to:

your_list = [
    set(['A', 'B', 'C', 'D']),
    set(['X', 'B', 'A']),
    set(['R', 'C', 'A', 'B', 'X'])
]

print(set.intersection(*your_list))

Note don't call your own variables list, as it collides with the built-in list type and will get really confusing.

solidpixel
  • 10,688
  • 1
  • 20
  • 33
1

If order doesn't matter, you can use set.intersection:

l = [['A', 'B', 'C', 'D'],
     ['X', 'B', 'A'],
     ['R', 'C', 'A', 'B', 'X']]

list2 = list(set.intersection(*(set(sl) for sl in l)))

print(list2)

Output:

['A', 'B']
#  or ['B', 'A']
DjaouadNM
  • 22,013
  • 4
  • 33
  • 55
0

Try this :

>>> list1 = [['A', 'B', 'C', 'D'], ['X', 'B', 'A'], ['R', 'C', 'A', 'B', 'X']]
>>> list2 = list(set(list1[0]).intersection(list1[1]).intersection(list1[2]))
>>> list2
['A', 'B']
Arkistarvh Kltzuonstev
  • 6,824
  • 7
  • 26
  • 56