Alex Rivera | Logout

In Python what's some other ways to write a if x==1 or x==5 or x==10...?

Asked 2012-04-08T18:47:12.520
9

I often end up writing code like

if x == 1 or x == 5 or x == 10 or x == 22 :
    pass

In English it seems redundant to keep repeating x, is there an easier or shorter way to write out an if-statement like that?

Maybe checking of existence of x's value in a tuple ( 1, 5, 10, 22, ) or something?

Edit
Report

1 Answer

6

You can use in with a collection:

if x in [1, 5, 10, 22]:
     # etc...

if x in {1, 5, 10, 22}:  # New syntax for creating sets  
     # etc...

Note that this will create a new list every time the line executes. If efficiency is a concern, create the collection only once and reuse it.

answered 2012-04-08T18:48:50.447

Your Answer