0

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.

8
  • 3
    I would 100% just make this a full function. lambdas lose their readability pretty quickly. Commented Jul 29 at 13:45
  • I have no idea what your lambda is doing and when it should return 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. Commented Jul 29 at 13:46
  • 2
    Shouldn't it be as simple as if/else? Why do you need to juggle and/ors? Commented Jul 29 at 13:46
  • 2
    Why not just use the native sum function? sum(tab)? Commented Jul 29 at 14:02
  • @trincot It's just an example... to illustrate the problem with 0 in this situation of using and and or. Commented Jul 29 at 14:05

1 Answer 1

1

I usually do it without or:

sum = lambda tab: len(tab) and tab[0] + sum(tab[1:])

print(sum([1, 2, 3]))

But if you insist on it:

sum = lambda tab: tab and tab[0] + sum(tab[1:]) or 0

print(sum([1, 2, 3]))
Sign up to request clarification or add additional context in comments.

2 Comments

I know the op used sum as the name of their function, but your answer might be used as a reference by many people in the future, and using sum as a name is bad practice in python since it shadows a builtin, so I recommend changing the name to anything else in your answer.
@Stef Yeah I'm not a fan of that, but I dislike mismatches between answers and questions more. Besides, who would use this instead of the built-in? And it even takes quadratic time and memory.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.