Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easier way to add multiple list items?

Tags:

python

Is there an easier way to sum together items from a list than the code I've written below? I'm new to this and this seems somewhat unwieldy.

n = [3,5,7]
o = [4,10,8]
p = [4,10,5]

lists = [n, o, p]

def sumList(x):
    return sum(x)


def listAdder(y):
    count = 0
    for item in y:
        count += sumList(item)
    return count

print listAdder(lists)
like image 747
jumbopap Avatar asked Nov 30 '22 04:11

jumbopap


1 Answers

Something like:

from itertools import chain

n = [3,5,7]
o = [4,10,8]
p = [4,10,5]

print sum(chain(n, o, p))
# 56

This avoids creating an un-necessary list of items, since you pass them to chain directly...

like image 64
Jon Clements Avatar answered Dec 06 '22 17:12

Jon Clements