Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concise way to compare a variable against multiple values [duplicate]

I've been trying to understand if it is possible to use an if statement similar to the likes of what I have demonstrated here below. It is my understand that it is not?

for i in range(10):
  if i == (3 or 5) or math.sqrt(i) == (3 or 5):
    numbers.append(i)

With this block of code I only get the numbers 3 & 9, while I should be getting 3, 5, 9. Is there another way of doing so without listing the code below?

for i in range(10):
  if i == 3 or i == 5 or math.sqrt(i) == 3 or math.sqrt(i) == 5:
    numbers.append(i)
like image 647
Revaliz Avatar asked Sep 15 '26 04:09

Revaliz


2 Answers

You can use in operator:

for i in range(10):
  if i in (3, 5) or math.sqrt(i) in (3, 5):
    numbers.append(i)

or in case you expect each of the calculations to be in the same group of results, you can use any()

results = [1, 2, ..., too long list for single line]
expected = (3, 5)

if any([result in expected for result in results]):
    print("Found!")

Just a minor nitpick, sqrt will most likely return a float sooner or later and this approach will be silly in the future, therefore math.isclose() or others will help you not to encounter float "bugs" such as:

2.99999999999999 in (3, 5)  # False

which will cause your condition to fail.

like image 98
Peter Badida Avatar answered Sep 16 '26 17:09

Peter Badida


if i == (3 or 5) or math.sqrt(i) == (3 or 5):

is equivalent to

if i == 3 or math.sqrt(i) == 3:

leading to 3 and 9 as results.
This because 3 or 5 is evaluated as 3 by being 3 the first non-zero number (nonzero numbers are considered True). For instance, 0 or 5 would be evaluated as 5.

like image 23
abc Avatar answered Sep 16 '26 17:09

abc



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!