For example, if I have the following statement:
if( foo1 or foo2)
...
...
if foo1 is true, will python check the condition of foo2?
Yes, Python evaluates boolean conditions lazily.
The docs say,
The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
This isn't technically lazy evaluation, it's short-circuit boolean expressions.
Lazy evaluation has a somewhat different connotation. For example, true lazy evaluation would likely allow this
def foo(arg) :
print "Couldn't care less"
foo([][0])
But Python doesn't.
Python is also nice in that it "echos" it's boolean arguments. For example, an or condition returns either it's first "truthy" argument or the last argument (if all arguments are "falsey"). An and condition does the inverse.
So "echo argument" booleans means
2 and [] and 1
evaluates to [], and
[] or 1 or 2
evaluates to 1
A short demo would be to compare the time difference between
all(xrange(1,1000000000))
and
any(xrange(1,1000000000))
The all() has to check every single value, whilst the any() can give up after the first True has been found. The xrange, being a generator, therefore also gives up generating things as soon as the evaluator is done. For this reason, the all will consume large amounts of RAM and take ages, whilst the any will use just a few bytes and return instantaneously.
help("or")
at the interpreter console. In this case, read the fourth paragraph. - DSMif
" and everything to do with "or
." - jwodderif
statement ... which is privileged (more than not or bool()), and so it evaluates them once. The double-evaluation depends on the complexity of the operation. This is counter intuitive, but there is proof here: gist.github.com/earonesty/08e9cbe083a5e0583feb8a34cc538010 - Erik Aronesty