Compare To Multiple Values In An If Statement
im going to need multiple if statements comparing to the same couple elements, and was wondering if there was something along these lines i could do to make the code cleaner and ea
Solution 1:
Use the in operator
if num in a :
as in
deftest(num):
a = [1, 2, 3]
if num in a :
returnTrueelse :
returnFalsea work around would be (as suggested by Padraic)
def test(num):
a = [1, 2, 3]
return num in a
This would work because, The in operator compares if the LHS is present in the RHS and returns a boolean value respectively.
Also this is possible
test = lambda x: num in [1, 2, 3]
That is all in a single line!
Solution 2:
You can use in, or check for the index and catch the error:
num in a will check if the item num is in the list a.
>>> 1in [1, 2, 5]
True>>> 3in [1, 2, 5]
False>>> 100inrange(101)
Truetry getting the index, and except to catch the IndexError:
defisIn(item, lst):
try:
lst.index(item)
returnTrueexcept ValueError:
returnFalsereturnFalse>>> isIn(5, [1, 2, 5])
True>>> isIn(5, [1, 2, 3])
False
Post a Comment for "Compare To Multiple Values In An If Statement"