1

I want to take multiple lists and know the values that appaer in these lists with the possibility of one or more of the lists being empty.

CASE 1:

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
c = []
d = [2, 3, 5]

Needed output: 5

CASE 2:

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5, 3]
c = [1, 3, 8]
d = []

Needed output: 3

Order doesn't matter. I know I can use this if there are no empty lists (source 1 / source 2)

list(set(a) & set(b) & set(c) and set(d))

The problem occurs when one of the lists is empty.

Python version: 3.8

RVE
  • 328
  • 4
  • 17
  • Is it mandatory that your solution should return intersection value only if one or more lists are non-empty? OR we need to simply discard the empty lists while calculation the intersection? – Moinuddin Quadri Feb 16 '21 at 14:27
  • Ideally, if there is nothing common among non empty lists, it should return an empty set right? The issue was that if a single one is empty, it always returns an empty set. Do confirm @RVE. Thanks – Akshay Sehgal Feb 16 '21 at 14:28
  • Only the empty lists needed to discarded. You'r solution works like a charm, thx! – RVE Feb 16 '21 at 15:13

2 Answers2

4

Lets use a list comprehension with set.intersection -

The list comprehension checks if the length of the list is greater than 0 and then uses it to find an intersection using set.intersection. The * operator unpacks this list of sets, to individual sets.

Case 1:

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
c = []
d = [2, 3, 5]

l = [a,b,c,d]
l = [set(i) for i in l if len(i)>0]
set.intersection(*l)
{5}

Case 2:

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5, 3]
c = [1, 3, 8]
d = []

l = [a,b,c,d]
l = [set(i) for i in l if len(i)>0]
set.intersection(*l)
{3}
Akshay Sehgal
  • 18,741
  • 3
  • 21
  • 51
1

You use filter() to remove empty lists and then convert your list to set() objects using map() and do the intersection as:

a = [1, 2, 3, 4, 5]
b = [9, 8, 7, 6, 5]
c = []
d = [2, 3, 5]

my_list = [a, b, c, d]

my_result = set.intersection(*map(set, filter(bool, my_list)))
# where `my_result` holds the value: 
#    {5}
Moinuddin Quadri
  • 46,825
  • 13
  • 96
  • 126