0

My question is it:

for me, these two options should do the same thing:

1)

if "a" in x or "b" in x or "c" in x:
  print ("xxxxxxxxx")

2)

if ("a" or "b" or "c") in X:
   print ("xxxxxxxx")

but when I run them the results are diferents. The first option work good for me, but the second no. I want print "xxxxx" if a or b or c is in x.

where is the problem???

thanks

ozo
  • 883
  • 1
  • 10
  • 18
  • 1
    The second one is completely invalid. Use the first until you learn the more succinct methods. – Carcigenicate Oct 18 '17 at 15:21
  • 3
    Very similar to [How do I test one variable against multiple values?](https://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) Not an exact duplicate, but the lesson from it applies here. – Carcigenicate Oct 18 '17 at 15:21
  • 1
    Why? `or` isn't a Boolean operator. `"a" or "b" or "c"` evalutes to `"a"`, and `or` is also not part of the `in` operator, so there's no reason for it to distribute like you want. – chepner Oct 18 '17 at 15:22
  • 2
    @Carcigenicate It's not at all invalid; it simply doesn't do what the OP expects. – chepner Oct 18 '17 at 15:22
  • 1
    @chepner Invalid in the sense that it doesn't do as they want. Yes, it's syntactically valid. – Carcigenicate Oct 18 '17 at 15:22
  • Try `if any(map(lambda i: i in x, ("a", "b", "c"))):` – Adirio Oct 18 '17 at 15:27
  • 1
    Suppose `x` is `['b', 'c']`. Then `("a" in x or "b" in x or "c" in x)` is equivalent to `("a" in ['b', 'c'] or "b" in ['b', 'c'] or "c" in ['b', 'c'])` which is equivalent to `(False or True or True)` which is equivalent to `True`. On the other hand, `(("a" or "b" or "c") in x)` is equivalent to `("a" in ['b', 'c'])` (because of [the way OR works](https://stackoverflow.com/questions/19213535/using-and-and-or-operator-with-python-strings#19213583)) which is equivalent to `False` – Bryant Oct 18 '17 at 15:41

0 Answers0