Simple question to which I can't find any "nice" answer by myself:
Let's say I have the following condition:
if 'foo' in mystring or 'bar' in mystring or 'hello' in mystring: # Do something pass
Where the number of or
statement can be quite longer depending on the situation.
Is there a "nicer" (more Pythonic) way of writing this, without sacrificing performance ?
If thought of using any()
but it takes a list of boolean-like elements, so I would have to build that list first (giving-up short circuit evaluation in the process), so I guess it's less efficient.
Thank you very much.
You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line. In the revised version of the script, a blank space and an underscore indicate that the statement that was started on line 1 is continued on line 2.
A way could be
if any(s in mystring for s in ('foo', 'bar', 'hello')): pass
The thing you iterate over is a tuple, which is built upon compilation of the function, so it shouldn't be inferior to your original version.
If you fear that the tuple will become too long, you could do
def mystringlist(): yield 'foo' yield 'bar' yield 'hello' if any(s in mystring for s in mystringlist()): pass
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With