What's the Pythonic way of flipping between two values?

Viewed 61

EDIT: My original question was a bit unclear, so I have updated it. Sorry for the inconvenience.

Suppose I have some different values: A, B, C, D, ..., and some variable x that is equal to one of these. Furthermore suppose I know that the opposite of A is B, the opposite of C is D, and so on.

What I want is some clean way of mirroring the boolean x = not x but for these generic values. Right now all I can think of is a horrible if-else chain:

if x == A:
    x = B
elif x == B:
    x = A
elif x == C:
    x = D
elif x == D:
    x = C
elif ...

To give some indication of what I'm after, in Haskell I could define this as as:

foo :: x -> x
foo A = B
foo B = A
foo C = D
foo D = C
...

and then simply call foo x.

3 Answers

Build a dict with 2-way mappings. Something like

pairs = [(A, B), (C, D), ...]
d = dict([*pairs, *map(reversed, pairs)])

Then x = d[x].

If for whatever reason you don't like the idea of instantiating a full list of the pairs and reversed pairs, you can use itertools.chain:

d = dict(chain(pairs, map(reversed, pairs)))

One way to do it is

x = B if x == A else A

After editing my question, I came to the realization I can do this:

def flip(x):
    if x == A: return B
    if x == B: return A
    if x == C: return D
    if x == D: return C
    ...

Still, if anyone knows of a better way, feel free to post an answer.

Related