Example of calling any
and all
:
print any(l == 't' for l in 'python') # Returns True. Same as: 't' in 'python'
print all(l == 't' for l in 'python') # Returns False. Not all of the letters are 't'.
True False
Example of constructing a generator with a generator expression:
g = (l == 't' for l in 'python')
print g.next() # False. 'p' is not equal to 't'
print g.next() # False. 'y' is not equal to 't'
print g.next() # True. 't' is equal to 't'
False False True
Example of using a generator with a for loop:
g = (l == 't' for l in 'python')
for value in g:
print value
False False True False False False
Example of calling any
and all
with various generators:
g = (l == 't' for l in 'python')
print any(g)
print any((l == 't' for l in 'python')) # same thing
print any(l == 't' for l in 'python') # same thing. No double parentheses
True True True
Illustrating how many values any
and all
consume before returning:
def t():
print 'In True!'
return True
def f():
print 'In False!'
return False
# Store functions to be called in a list
funcs = [t, f, f, f, t]
def test_any():
# Pass a generator expression with function calls to any
print 'Testing any:'
print any(func() for func in funcs)
print 'done.\n\n'
def test_all():
# Pass a generator expression with function calls to all
print 'Testing all:'
print all(func() for func in funcs)
print 'done.\n\n'
test_any() # Calls t() once and stops.
test_all() # Calls t(), then f(), then stops
Testing any: In True! True done. Testing all: In True! In False! False done.