Search code examples
pythonlistfor-loopcontrol-flowbuilt-in-types

Using 'for loop' to sum nested list values and return (total of sum)


I am receiving the count of each line in each list, I am looking to sum each particular values of entire list, (Nested lists included)

[[3],[4],][1],[3]] = * 11 is my desired result.

example: code

ar1 = [
          ['jam','apple','pear'],
          ['toes','tail','pinky','liar'],
          ['aha!'],
          ['jam','apple','pear']
      ]

def function(arg1)
    heads = 0
    for i in arg1:
        heads += arg1.count(i)
        print heads

I have used this print because i dont know how to compile and debug any other for than the print statement and recheck work, so please no flaming.(newbie alert)

example: result

['jam','apple','pear']     1
['toes','tail','pinky','liar']    2
['aha!']     3
['jam','apple','pear']    4

I prefer a hint, or hints to what methods i should be applying or an example. I am in no way expecting a solution. I


Solution

  • You have some choices :

    1.flatten your nested list and calculate the length of total list:

    >>> len(reduce(lambda x,y:x+y,ar1))
    11
    

    Or you can loop over your list and sum the length of all your sub-lists you can do it with a generator expression within sum function :

    >>> sum(len(i) for i in ar1)
    11