1
list(set(a[0]) & set(a[1]) & set(a[2]) & set(a[3]) & set(a[4]))

Does anyone know how to write this in a way such that we dont need to know apriori how many lists we will be given? (ie 5 not hard coded in)?

Each a is a list of varying size.

Trajan
  • 1,380
  • 6
  • 20
  • 41

2 Answers2

3

As long as you have at least one set, you can do this:

list(set(a[0]).intersection(*a[1:]))

If there might be no sets, you have to decide for yourself what the "intersection of no sets" actually should mean in your application. If you want the empty set:

list(set(*a[:1]).intersection(*a[1:]))
wim
  • 338,267
  • 99
  • 616
  • 750
  • 2
    If the list contains at least one set you don't need to slice the list at all. `list(set.intersection(*a))` will do. If the list can be empty then do: `a and list(set.intersection(*a))`. – blhsing Dec 10 '19 at 22:17
  • @blhsing True, but only by accident. And I have seen many times the bug that people don't understand ("descriptor 'intersection' of 'set' object needs an argument"). Better to have an `IndexError` here instead. – wim Dec 10 '19 at 22:32
0

I think it's worth noting, at least to improve one's general programming understanding, that what you want to do can be described as mapping and then reducing or folding. Specifically, you want to map set over a and then fold & over the result.

I'm not a Python expert, but it can be done like this in Python:

from functools import reduce

a = [
    [1,2,3],
    [1,2,3,4],
    [1,2,4,5],
    [1,2,3,5],
]

intersection = lambda x, y: x & y

mapped = list(map(set, a))

reduced = reduce(intersection, mapped)

Note that this implementation requires a to be non-empty.

Simon Alling
  • 531
  • 7
  • 14
  • If you insist to do it like this, use [`operator.and_`](https://docs.python.org/3/library/operator.html#operator.and_). Don't bind lambdas to names. – wim Dec 10 '19 at 22:15
  • I don't insist on actually doing it like that in Python, just want to demonstrate the general concept. Anyway, thanks for the heads-up! Didn't know about `operator`. Why shouldn't I bind lambda expressions to names though? – Simon Alling Dec 10 '19 at 22:20
  • Because then they cease to be anonymous functions. It can be a def instead, which are less crippled in Python. – wim Dec 10 '19 at 22:34