0

I have the following code:

if <one-string> in x and <another-string> in x:
    <do something>

I hate the duplication of comparing two values to the same variable in two separate steps. But I can't iterate over the strings because I still end up with two booleans that must then be compared for a final boolean value. Is there a pythonic way of doing this?

  • You know, from a Python perspective, this is the better way to write it. It may take more keystrokes, but it looks neater, is more readable, and does exactly what it looks like it should do. I use this a **lot**, even though I will admit it does get annoying. – Levi Lesches Feb 26 '18 at 00:06
  • Possible duplicate of [How to check if one of the following items is in a list?](https://stackoverflow.com/questions/740287/how-to-check-if-one-of-the-following-items-is-in-a-list) – Ken Y-N Feb 26 '18 at 00:07
  • 2
    You could use `all()`, but your code is already Pythonic and is more readable than using `all(s in x for s in candidate_strings)`. If you had more than 2 stings to compare then the case would be different. – mhawke Feb 26 '18 at 00:07
  • If you only have two values to check, what you have above is is much better than trying to do some sort of list comprehension. Its much more readable. – Sean Breckenridge Feb 26 '18 at 00:12

2 Answers2

0

You can do that using set():

your_strings = ['one-string', 'another-string']
if len(set(your_strings) & set(x)):
    # do something
kiyah
  • 1,502
  • 2
  • 18
  • 27
0

Just use the appropriate function to collapse all the booleans into one.

if all(s in x for s in ('foo', 'bar')):
   ...

if not any(s in x for s in ('foo', 'bar')):
   ...
Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • I like this approach. It's fairly straightforward without the seeming duplicate process, but I think Levi Lesches' reasoning may appeal to me more - readability. I am not far beyond just literate in Python (my first program language since Basic), and I just may confuse myself going back to my code later using the 'all' and 'any' approach. Or maybe not. I'll need to cogitate on it for a while ;). Thanks. – long_time_newbie Feb 26 '18 at 00:23