1

I have many sets and would like to know if they have any intersection. Currently the following code is used:

if reduce(set.intersection, mysets):
    ...

Is there a better way to do this? I somehow heard reduce is not good to use. But it seems to fit this scenario quite well.

martineau
  • 119,623
  • 25
  • 170
  • 301
nos
  • 19,875
  • 27
  • 98
  • 134

1 Answers1

1

IMHO reduce is perfectly fine to use (You might want to use functools.reduce going into Python3). The sets should be ordered to shrink as fast as possible (i.e. having mostly disjoint sets first if possible) but this might require a-priori knowledge you may not have.

However, If you're using a version after Python2.6, the answer to this question notes that you can use set.intersection. You would call this then by using set.intersection(*mysets).

The answer then is:

Pre-2.6: use reduce

Post-2.6: use set.intersection

Snakes and Coffee
  • 8,747
  • 4
  • 40
  • 60