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
do what you want.
Cameron Simpson email@example.com
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
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.
Would it be useful to extend the standard library’s
sum() by a keyword argument like