Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which is better in python? [closed]

I have used some conditions statements in python which gives the same result. I would like to know which is better and what is the difference in performance and logic between them.

Case 1:

if a and b and c:
    #some action

vs

if all( (a, b, c) ):
    #some action

Case 2:

if a or b or c:
    #some action

vs

if any( (a, b, c) ):
    #some action

Case 3:

if not x in a:
    #some action

vs

if x not in a:
    #some action

In the above cases, I would like know about the difference in performance and logic and preferred way.

like image 307
arulmr Avatar asked Jun 11 '26 01:06

arulmr


1 Answers

Case 1

From https://docs.python.org/2/library/functions.html#all

all(iterable)

Return True if all elements of the iterable are true (or if the iterable is empty). Equivalent to:

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

This means if a and b and c: and if all( (a, b, c) ): do the same thing (duh) but all() involves a function call and a loop, so it's bound to be a little slower, but really, just a tiny bit.

I'd say you use if a and b and c: if you have only a couple variables (no more than 3) to keep it readable and all() if you have more.

Keep in mind: readability is almost always more important than a minor performance improvement.

all() and any() can take a list comprehension as input which is really useful.

Note: all() is only available in Python 2.5+


Case 2

Same as case 1, really. Because it's almost the exact same function

any(iterable)

Return True if any element of the iterable is true. If the iterable is empty, return False. Equivalent to:

def any(iterable):
    for element in iterable:
        if element:
            return True
    return False

Note: any() is only available in Python 2.5+


Case 3

From http://legacy.python.org/dev/peps/pep-0008/#programming-recommendations

Use is not operator rather than not ... is. While both expressions are functionally identical, the former is more readable and preferred.

You should use if x not in a: over if not x in a:, because the styleguide is holy

like image 132
Tim Avatar answered Jun 12 '26 14:06

Tim