Python sum none instead of zero

Hello I ama a begginer python user and is windering if is it possible to None instead of zero in summing in lists through loops ?

Hi and welcome.

I appreciate that English may not be your 1st language, but you’re doing okay.

Maybe an example of what you’re looking for (which is a little unclear to me, but may be clear to others) in terms of a list for the input, what output you’re getting, and what output you need.

By Arboraevo via Discussions on Python.org at 20Jun2022 22:38:

Hello I ama a begginer python user and is windering if is it possible
to None instead of zero in summing in lists through loops ?

Please be more clear. Maybe provide an example list you want to “sum”
and also tell us what outcomes you want, and how plain sum() doesn’t
do what you want.

Cheers,
Cameron Simpson cs@cskk.id.au

Do you mean something like this?

items = [1, 2, 4, 8]
print(sum(items))  # prints 15

items = []
print(sum(items))  # prints 0

items = []
print(sum(items) or None)  # prints None

Otherwise I don’t understand your question.

I guess the problem @arboraevo is trying to resolve is that this would give None too:

items = [1, -1]
print(sum(items) or None)  # prints None

To resolve this you can:
a) Use a condition like:

items = [1, -1]
print(sum(items) if items else None)  # prints 0

b) Create a wrapper around sum(). This (like the code above) does not work with iterators!

def sum2(sequence, empty_default=None, **kwargs):
    return sum(sequence, **kwargs) if sequence else empty_default

c) Create your own sum() variant which would also work with iterators. Leaving as an exercise. :slight_smile:

Would it be useful to extend the standard library’s sum() by a keyword argument like empty_default=None?