Does Python evaluate if's conditions lazily?
Does Python evaluate if's conditions lazily?
--
Become part of the top 3% of the developers by applying to Toptal
https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Magic Ocean Looping
--
Chapters
00:00 Question
00:22 Accepted answer (Score 107)
00:57 Answer 2 (Score 63)
01:10 Answer 3 (Score 24)
01:35 Answer 4 (Score 6)
02:31 Thank you
--
Full question
https://stackoverflow.com/questions/1396...
Accepted answer links:
[docs say]: http://docs.python.org/2/reference/expre...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #lazyevaluation
ACCEPTED ANSWER
Score 115
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.
ANSWER 2
Score 77
and or is lazy
& | is not lazy
ANSWER 3
Score 25
Python's laziness can be proved by the following code:
def foo():
print('foo')
return False
def bar():
print('bar')
return False
foo() and bar() #Only 'foo' is printed
On the other hand,
foo() or bar()
would cause both 'foo' and 'bar' to be printed.
ANSWER 4
Score 7
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