1. This site uses cookies. By continuing to use this site, you are agreeing to our use of cookies. Learn More.
  2. Anuncie Aqui
    Anuncie aqui você Também: fdantas@4each.com.br

[Python] Python lambda returns 0

Discussão em 'Python' iniciado por Stack, Julho 29, 2025.

  1. Stack

    Stack Membro Participativo

    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.

    Continue reading...

Compartilhe esta Página