This is actually question about the semantics of set comprehensions, but I first need to explain the context. I'm trying to create a new set of tuples where the paired value in the touple is unique regardless of the order of the values in the pair. Simplifying my actual program, what I have is something like {(1, 2), (2, 1), (3, 4)}
and I'd like to get {(1, 2), (3, 4)}
I tried doing something like this:
oldSet = {(1, 2), (2, 1), (3, 4)}
newSet = set()
newSet = {(val1, val2) for (val1, val2) in oldSet if not (val2, val1) in newSet}
However, newSet
is {(1, 2), (2, 1), (3, 4)}
, implying that something is wrong with my conditional expression. My understanding of comprehensions suggests that the above is syntactic sugar for something like this:
newSet = set()
for (val1, val2) in oldSet:
if not (val2, val1) in newSet:
newSet.add((val1, val2))
This traditional looping structure works (newSet
is {(1, 2), (3, 4)}
). Is there something about comprehensions that causes the conditional to be evaluated before newSet
has any members? I'm fairly new to Python, so I'm wondering if there's something subtle I'm missing.
Thanks!