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?
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.")
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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With