I saw it from Python Cookbook:
def sum(items):
head, *tail = items
return head + sum(tail) if tail else head
items = [1, 10, 7, 4, 5, 9]
print(sum(items)) #36
It says it's some kind of clever recursive algorithm.
It's a conditional expression:
A if PREDICATE else B
A is yielded if PREDICATE
is true, otherwise B is yielded.
>>> 'A' if 1 < 2 else 'B'
'A'
>>> 'A' if 1 > 2 else 'B'
'B'
sum(tail)
is part of the expression as well.
The structure of this expression is:
result = Val1 if condition else Val2
and it equivalent to:
if (condition):
result = Val1
else:
result = Val2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With