Is there a simple way to return 0 with a lambda
function using and
and or
operators?
For example, consider this function to sum elements in an array:
sum = lambda tab: tab == [] and 0 or tab[0] + sum(tab[1:])
Neutral element for number addition is 0 so it produces an IndexError
: 0 is a falsy value.
Thus with multiplication it works:
>>> prod = lambda tab: tab == [] and 1 or tab[0] * prod(tab[1:])
>>> prod([1, 2, 3])
6
Other numbers than 0, for example 1, are truthy.
lambda
s lose their readability pretty quickly.0
. Maybe first write it as normal function - so you could use print() to test values - and later try to reduce it to one line.if/else
? Why do you need to juggleand
/or
s?sum
function?sum(tab)
?and
andor
.