2

Is there a more elegant way to toggle between two strings or integers in Python 3?

x={"A":"B", "B":"A"}[x]

The values can be non-boolean, like string or integer. Let's suppose that we want to toggle between "A" and "B" and the variable name is x.

In other words: if x = "A" then the result should be x = "B" and if x = "B" then the result should be x = "A".

input:

x="B"

output:

x="A"
2
  • what is the output you want to achieve ?
    – user5777975
    Commented Jun 7, 2018 at 12:36
  • if x ="A" then the result should be x="B" and if x="B" then the result should be X="A" Commented Jun 7, 2018 at 12:51

2 Answers 2

2

Using a dict is already pretty smart. Here is an alternative:

x = 'B' if x == 'A' else 'A'
2
  • Goswin, I like your solution too. which one do you think makes the code more readable? Commented Jun 7, 2018 at 14:55
  • I think the "if" is better because it will recover from an invalid value. Commented Jun 7, 2018 at 21:36
0

You can write something like that:

def toggle(x):
    x['A'], x['B'] = x['B'], x['A']

x = {'A': 'B', 'B': 'A'}

or that:

def toggle(x):
    x.update(dict(zip(x.keys(), list(x.values())[::-1])))

x = {'A': 'B', 'B': 'A'}

print(x)
toggle(x)
print(x)
toggle(x)
print(x)

OUTPUT:

{'A': 'B', 'B': 'A'}
{'A': 'A', 'B': 'B'}
{'A': 'B', 'B': 'A'}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.