Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summing nested lists without recursion in python

Given a Python list whose elements are either integers or lists of integers (only we don't know how deep the nesting goes), how can we find the sum of each individual integer within the list?

It's fairly straightforward to find the sum of a list whose nesting only goes one level deep, but what if the nesting goes two, three, or more levels deep?

I know the best approach is recursion, but this is a challenge wherein I have to do it without recursion.

Please help!!

like image 985
thorium Avatar asked Apr 01 '26 08:04

thorium


1 Answers

L = [...]
while any(isinstance(i, list) for i in L):
   L = [j for i in L for j in (i if isinstance(i, list) else [i])]

result = sum(L)

Basically you iterate over the outer list and unpack the first level of any inner lists until there are no inner lists left

like image 75
John La Rooy Avatar answered Apr 03 '26 21:04

John La Rooy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!