I’ve recently made the following example for Pythons for … else:
def isPrime(element):
""" just a helper function! don't get religious about it! """
if element == 2:
return True
elif element <= 1 or element % 2 == 0:
return False
else:
for i in xrange(3, element, 2):
print i
if element % i == 0:
return False
return True
myList = [4, 4, 9, 12]
for element in myList:
if isPrime(element):
break
else:
print("The list did not contain a prime.")
A fellow student told me, that this task can be done with Scala like this:
List(4, 4, 9, 12) exists isPrime
Which gets lazy evaluated.
Does something similar like the exists-keyword exist in Python? Or is there a PEP for that?
Python also has
all()which cranks through any sequence and returnsTrueif all elements evaluate true.any()andall()both have short-circuit evaluation: ifany()finds any element that evaluates true, it stops and returnsTrue; and ifall()finds any element that evaluates false, it stops and returnsFalse.Both are “lazy” in that they use Python iteration to pull values one at a time. For example:
This will iterate until a non-prime number is found, then return
False. It prints the numbers as a side-effect so you can watch it work. I just tried this and got:P.S. I went to a talk at a Python conference, and the speaker mentioned that he commonly uses
any()as a very efficient way to do a loop. Aforloop re-binds the loop variable for each loop, butany()doesn’t do that; it just keeps checking values. So if you useany()with a function that always returnsNoneor a false value, it will iterate its way all to the end of the sequence, and according to that guy, it’s the fastest way in Python to do it. (And if your function returns a value that is notNoneand isn’t false, you can useall()for the same trick. The only time it doesn’t work is if sometimes the function returns a true value and sometimes it returns a false value. But you can force it to always work:P.P.S. Let’s use
all()to rewriteisPrime()! I’ll change the name tois_prime()to conform to PEP 8. http://www.python.org/dev/peps/pep-0008/