Whenever you need an expression in which two things must be true. For example:
# you want to see only odd numbers that are in both lists list1 = [1,5,7,6,4,9,13,519231] list2 = [55,9,3,20,18,7,519231] oddNumsInBothLists = [element for element in set(list1) if element in set(list2) and element % 2]
Boolean operators, in particular, and, can usually be omitted due to readability. The built-in function all() will return true if and only if all its members are true. Similarly, the any() function will return true if any of its members is true.
shouldBeTrue = [foo() for foo in listOfFunctions] if all(shouldBeTrue): print("Success") else: print("Fail")
Perhaps an easier way to think that or will be used instead of consecutive if statements, while and will be used instead of nested if statements.
def foobar(foo, bar): if(foo): return foo if(bar): return bar return False
functionally identical:
def foobar(foo, bar): return foo or bar
and
def foobar(foo, bar): if(foo): if(bar): return bar return False
functionally identical:
def foobar(foo, bar): return foo and bar
This can be demonstrated with a simple test.
class Foo: def __init__(self, name): self.name = name test1 = Foo("foo") test2 = Foo("bar") print((test1 or test2).name)