Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't understand this Python sentence 'if tail else head'

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.

like image 456
Jeff Liu Avatar asked Sep 28 '14 14:09

Jeff Liu


2 Answers

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'
like image 125
falsetru Avatar answered Sep 28 '22 15:09

falsetru


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
like image 37
Elisha Avatar answered Sep 28 '22 15:09

Elisha