5

I've created a list of sets that I'd like to pass into set.intersection()

For example:

List_of_Sets = [{1,2,3},{3,4,5},{5,6,7}]
set.intersection(List_of_Sets)

Result:

TypeError: descriptor 'intersection' requires a 'set' object but received a 'list'

Desired Output:

{3,5}

How would I pass each set within the list as a separate argument into set.intersection()?

Puffin GDI
  • 1,702
  • 5
  • 27
  • 37
Chris
  • 5,444
  • 16
  • 63
  • 119
  • 1
    Please explain the operation you want to implement. `{1,2,3} intersect {3,4,5} intersect {5,6,7}` does not result with `{3,5}` but with `{}`... – shx2 Jan 24 '14 at 07:27
  • 1
    @mgilson I'm not sure about the dups, the answers are identical, but the questions are not. – Steinar Lima Jan 24 '14 at 07:27
  • @SteinarLima, but then do we allow every unpacking question so long as it applies to a new function? – mhlester Jan 24 '14 at 07:28
  • @mhlester I don't know. Meta has probably some discussions regarding it. – Steinar Lima Jan 24 '14 at 07:29
  • @SteinarLima -- I've seen questions closed with less similarity than this before, but as always, my 1 close vote isn't enough. We still need 4 more ;-). It's up to the *community* to decide. – mgilson Jan 24 '14 at 07:36

2 Answers2

7

Use the unpacking operator: set.intersection(*List_of_Sets)


As pointed out in the other answer, you have no intersections in the list. Do you want to compute the union of the intersection of adjacent elements?

>>> set.union(*[x & y for x, y in zip(List_of_Sets, List_of_Sets[1:])])
set([3, 5])
mgilson
  • 300,191
  • 65
  • 633
  • 696
  • Or, if you *really* like `map` instead: `set.union(*map(operator.__and__,*zip(List_of_Sets, List_of_Sets[1:])))` – mgilson Jan 24 '14 at 07:35
2
>>> List_of_Sets = [{1,2,3},{3,4,5},{5,6,7}]
>>> set.intersection(*List_of_Sets)  # * unpacks list into arguments
set([])

There are no intersections in that set so it returns an empty set. A working example:

>>> List_of_Sets2 = [{1,2,3},{3,4,5},{5,6,3}]
>>> set.intersection(*List_of_Sets2)  # * unpacks list into arguments
set([3])

Docs on unpacking with *

mhlester
  • 22,781
  • 10
  • 52
  • 75