0

What "If tail else head" do? If I take it out, it shows an error: ValueError: not enough values to unpack (expected at least 1, got 0)

items = [1, 10, 7, 4, 5, 9]

def sum(items):  
    head, *tail = items
    return head + sum(tail) if tail else head  

sum(items)
Atlas Yu
  • 11
  • 1
  • Briefly: that is Python's ternary operator. If `tail` is truthy, `sum(tail)` will be used. If it isn't, `head` will be used. – TigerhawkT3 Apr 13 '16 at 23:20
  • Why it shows not enough values to unpack (expected at least 1, got 0) when I take "if tail else head" out? – Atlas Yu Apr 13 '16 at 23:22
  • Because sometimes `sum(tail)` doesn't have enough values to unpack in `head, *tail = items`. `tail` being falsey would mean it's an empty `list`, which can't be unpacked into at least one item as required. That's when the recursion ends by returning `head + head` instead of `head + sum(tail)`. – TigerhawkT3 Apr 13 '16 at 23:29

0 Answers0