3

I'm really stuck in evaluating Boolean expressions. See the code:

def f(A):
    if A=='a' or A=='b' or A=='c' ...:
        return True
    return False

Is there any convenient and elegant way to do this when A can equal to even more strings?

YiFei
  • 1,752
  • 1
  • 18
  • 33

3 Answers3

7

If you do this check often and/or have a lot of possible values consider using a set. Lookup time for a set is O(1), lookup time for a list is O(n).

if A in {'a', 'b', 'c', ...}:
    # do something
timgeb
  • 76,762
  • 20
  • 123
  • 145
6

You can do

if A in ["a", "b", "c"]:
    # do the thing

Since you are just returning the truth value, you can do

def f(A):
    return A in ["a", "b", "c"]

The in operator returns a boolean.

Mad Physicist
  • 107,652
  • 25
  • 181
  • 264
-2

Mad Physicist gave the usual way it's done.

Here's another:

if any(A == thing for thing in ('a', 'b', 'c')):
    # do stuff

This way isn't recommended for your specific example. It's more complicated. But sometimes, for more complicated situations, something similar to the above is useful.

Rick
  • 43,029
  • 15
  • 76
  • 119
  • 2
    That is exactly what `in` does. `in` works on any iterable, basically anywhere a comprehension does. – Mad Physicist Jan 10 '16 at 02:33
  • @MadPhysicist I understand. But it's different syntactically, and more complicated than the usual way. I gave it as an example because it's good for someone new to the language to see other ways of doing the same thing. – Rick Jan 10 '16 at 02:39
  • The concept of Pythonic is that there is one obvious way to do things. Making something more complicated with no added benefit is the opposite of what you want to show someone who is new to the language. – Mad Physicist Jan 10 '16 at 03:09
  • @MadPhysicist I don't agree. I do agree, and specifically said that it isn't the way it should be done. I don't agree (as a recent former newb myself) that showing other ways of doing things is ill-advised, as long as you make it clear that it isn't the right way. I also don't agree there is no added benefit. The op said they are stuck on evaluating Boolean expressions. It's the exact point in time you want to introduce the `any` function to a learning user. I understand why you're down voting the answer, I simply think you're wrong. – Rick Jan 10 '16 at 06:19