Skip to content

Instantly share code, notes, and snippets.

@edelooff
Last active June 4, 2020 22:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edelooff/2738a33ea1c7e8b4832e3f862ad5b6ee to your computer and use it in GitHub Desktop.
Save edelooff/2738a33ea1c7e8b4832e3f862ad5b6ee to your computer and use it in GitHub Desktop.
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