Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any nicer way to write successive "or" statements in Python?

Tags:

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.

like image 485
ereOn Avatar asked Jun 25 '12 12:06

ereOn


People also ask

How do you write multiple statements in Python?

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.


1 Answers

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 
like image 103
glglgl Avatar answered Oct 14 '22 02:10

glglgl