Search code examples
pythonsumnested-listselementwise-operationsstrerror

Element-wise sum of nested lists


I have a nested list called list_6:

[[-1, 1, -1, 1, -1, 1, 1, 0, -1, 0, -1, -1, 1, 1, 1, 0, 1, -1, -1, -1, 1, 1, 1, 0, 0, -1, 0, 0, 0, 1, 0, -1, 1, 1, -1, 0, 0, 1, 1, -1, 0, -1, 1, 1, -1, 1, -1, -1, -1, 1, -1],...]]

each element of the list contains integers from -1,1, and the elements are of unequal length, there are 20 elements in the list

I would like to create a new list called list_7 that looks like:

[[13],[4],[5],...]], so that each element in the nested list is summed, and the result is printed. I tried using iter.zip_longest:

[sum(i) for i in itertools.zip_longest(*list_6, fillvalue=0)]

but am getting an error function:

'str' object is not callable


Solution

  • You can do this using list comprehension https://www.programiz.com/python-programming/list-comprehension

    list_7 = [sum(inner_list) for inner_list in list_6]

    Within the brackets ([]) you are iterating over each item in list_6. Since each item in list_6 is itself a list (inner_list) we can call python's sum function on the list to get the sum of the values within inner_list https://www.w3schools.com/python/ref_func_sum.asp.

    I see now that you were looking for the sums to be lists themselves ([[13],[4],[5],...]],) in which case you would want to do:

    list_7 = [[sum(inner_list)] for inner_list in list_6]

    Putting brackets around sum(inner_list) creates a new list whose only entry is the sum of the inner_list.