Sum a list which contains None in Python

Last updated: Jul 4, 2022

Check out my new book

Sum a list which contains None in Python#

To sum a list which contains `None` values:

1. Use the `filter()` function to remove `None` values from the list.
2. Pass the `filter` object to the `sum` function.
3. The `sum` function will sum the numbers from the list.
main.py
```Copied!```my_list = [2, None, 4, None, 6, None]

total = sum(filter(None, my_list))

print(total)  # 👉️ 12
``````

We used the `filter()` function to remove `None` values from the list.

The filter function takes a function and an iterable as arguments and constructs an iterator from the elements of the iterable for which the function returns a truthy value.

If you pass `None` for the function argument, all falsy elements of the iterable are removed.

main.py
```Copied!```my_list = [2, None, 4, None, 6, None]

# 👇️ [2, 4, 6]
print(list(filter(None, my_list)))
``````

All values that are not truthy are considered falsy. The falsy values in Python are:

• constants defined to be falsy: `None` and `False`.
• `0` (zero) of any numeric type
• empty sequences and collections: `""` (empty string), `()` (empty tuple), `[]` (empty list), `{}` (empty dictionary), `set()` (empty set), `range(0)` (empty range).

The last step is to pass the `filter` object to the `sum()` function.

main.py
```Copied!```my_list = [2, None, 4, None, 6, None]

total = sum(filter(None, my_list))

print(total)  # 👉️ 12
``````

The sum function takes an iterable, sums its items from left to right and returns the total.

main.py
```Copied!```print(sum([2, 4, 6])) # 👉️ 12
``````

The `sum` function takes the following 2 arguments:

NameDescription
iterablethe iterable whose items to sum
startsums the `start` value and the items of the iterable. `sum` defaults to `0` (optional)
Use the search field on my Home Page to filter through my more than 3,000 articles.