Skip to content

Instantly share code, notes, and snippets.

@edelooff

edelooff/deep_add.py

Last active Jun 4, 2020
Embed
What would you like to do?
Sum any nested level of iterables, with optional initial value
from collections.abc import Iterable
def deep_add(*values, start=None):
def _traverser(parts):
for part in parts:
if isinstance(part, Iterable):
yield from _traverser(part)
else:
yield part
ivalues = _traverser(values)
if start is None:
try:
start = next(ivalues)
except StopIteration:
start = 0
return sum(ivalues, start)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment