Syntax of union of several sets

40 Views Asked by At

I would like to understand why is this a valid syntax:

common = (set(classes['Biology']) & set(classes['Math']) & set(classes['PE']) & set(classes['Social Sciences']) & set(classes['Chemistry']))

but not this:

common = set(classes['Biology']) & set(classes['Math']) & set(classes['PE'] & set(classes['Social Sciences']) & set(classes['Chemistry'])

TL;DR

Why is there a need to put all the unions into normal braces

()

Thank you.

1

There are 1 best solutions below

3
On

The second one is invalid because it's missing a close paren on set(classes['PE']. You don't need the outer parentheses, you just need to close the inner ones correctly.

Side-note: Performance-wise, you'd likely save a little by only explicitly converting the first item to a set, then using the intersection (which takes an arbitrary number of iterable arguments) to do the rest of the work in a single Python function call:

common = set(classes['Biology']).intersection(classes['Math'], classes['PE'], classes['Social Sciences'], classes['Chemistry'])