Any time you need a statement where two things should 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]
# => oddNumsInBothLists = [7, 9, 519231]
Boolean operators, particularly the and, can generally be omitted at the expense of readability. The builtin function all()
will return true if, and only if, all of its members are true. Similarly, the function any()
will return true if any of its members are true.
shouldBeTrue = [foo() for foo in listOfFunctions]
if all(shouldBeTrue):
print("Success")
else:
print("Fail")
Perhaps an easier way of thinking about it is that or
would be used in place of successive if-statements whereas and
would be used in place of nested if-statements.
def foobar(foo, bar):
if(foo):
return foo
if(bar):
return bar
return False
is functionally identical to:
def foobar(foo, bar):
return foo or bar
And:
def foobar(foo, bar):
if(foo):
if(bar):
return bar
return False
is functionally identical to:
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) # => foo
print((test1 and test2).name) # => bar
print((not test1 and not test2).name) # => AttributeError for 'bool' (False)