Search code examples
pythoncoding-stylecomparisonreadability

Python multiple comparisons style?


I am wondering if there is a way to do the following in a more compact style:

if (text == "Text1" or text=="Text2" or text=="Text3" or text=="Text4"):
    do_something()

The problem is i have more than just 4 comparisons in the if statement and it's starting to look rather long, ambiguous, and ugly. Any ideas?


Solution

  • How about this:

    if text in ( 'Text1', 'Text2', 'Text3', 'Text4' ):
        do_something()
    

    I've always found that simple and elegant.