Question

I'm not talking about the ternary operator. Can I write an if else statement in one line outside of a value expression? I want to shorten this code.

if x == 'A':
    return True
if x == 'B':
    return True
if x == 'C':
    return True
return False
Was it helpful?

Solution

You can use the in operator like this:

return x in ('A', 'B', 'C')

For Python 3.2+:

return x in {'A', 'B', 'C'}

From docs:

Python’s peephole optimizer now recognizes patterns such x in {1, 2, 3} as being a test for membership in a set of constants. The optimizer recasts the set as a frozenset and stores the pre-built constant.

Now that the speed penalty is gone, it is practical to start writing membership tests using set-notation.

OTHER TIPS

You can shorten your code by using in:

return x in ("A", "B", "C")

Or, if x is a single character:

return x in "ABC"

If your checks are more complicated than membership in a set and you want to reduce the number of lines of code, you can use conditional expressions:

return True if x == 'A' else True if x == 'B' else True if x == 'C' else False

If you need to apply the same test for many items in a sequence, you may want to use the any function:

return any(x == c for c in "ABC")

This will work for tests that are more complex that equality (so that in can't handle them) and for sequences that are too long for chained conditional expressions. Consider a "near equality" test for floating point numbers:

return any(abs(x - n) < epsilon for n in big_sequence_of_floats)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top