Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 428
hobbes3 Avatar asked Apr 08 '12 18:04

hobbes3


People also ask

How do you write an IF ELSE statement in Python?

Here's an example:if 51<5: print("False, statement skipped") elif 0<5: print("true, block executed") elif 0<3: print("true, but block will not execute") else: print("If all fails.")

What does x == Y mean in Python?

x = y, means that the value of x becomes the value of y. x == y compares the two values and returns true if they are equal and false if they are different. 28th July 2018, 6:38 AM.

What does number 2 == 1 mean in Python?

Therefore the (if number%2 == 1) function tests to see if the number is odd. If it returns true then your program continues and print the number. If the number is not odd the program ends. Follow this answer to receive notifications.

What does [:] do in Python?

A shortcut way to copy a list or a string is to use the slice operator [:] . This will make a shallow copy of the original list keeping all object references the same in the copied list.


3 Answers

Yes, you are right - either in a tuple or (if this check is made repeatedly) in a set.

So either do

if x in (1, 5, 10, 22):
    pass

or, if you do this check often and the number of values is large enough,

myset = set((1, 5, 10, 22))

[...]

if x in myset:
    pass

The myset stuff is the more useful, the more values you want to check. 4 values are quite few, so you can keep it simple. 400 values and you should use the set...

Another aspect, as pointed out by Marcin, is the necessary hashing for lookup in the set which may be more expensive than linearly searching a list or tuple for the wanted value.

like image 100
glglgl Avatar answered Nov 16 '22 21:11

glglgl


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.

like image 42
Mark Byers Avatar answered Nov 16 '22 21:11

Mark Byers


If you need good performance and are going to repeat the same comparison several times, use a set:

s = frozenset([1, 5, 10, 22]) # at the beginning

if x in s: # in your code
    pass
like image 30
Óscar López Avatar answered Nov 16 '22 20:11

Óscar López