Path: csiph.com!v102.xanadu-bbs.net!xanadu-bbs.net!news.glorb.com!diesel.cu.mi.it!.POSTED!not-for-mail From: pecore@pascolo.net Newsgroups: comp.lang.python Subject: Re: list comprehension return a list and sum over in loop Date: Sat, 13 Dec 2014 13:38:53 +0100 Organization: The Sun and the Rain. Lines: 39 Message-ID: <87zjar3esi.fsf@pascolo.net> References: NNTP-Posting-Host: ppp-99-14.21-151.libero.it Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Trace: virtdiesel.mng.cu.mi.it 1418474334 15062 151.21.14.99 (13 Dec 2014 12:38:54 GMT) X-Complaints-To: abuse@diesel.cu.mi.it NNTP-Posting-Date: Sat, 13 Dec 2014 12:38:54 +0000 (UTC) User-Agent: Gnus/5.101 (Gnus v5.10.10) XEmacs/21.5-b34 (linux) Cancel-Lock: sha1:3jzKHUrYA8Ir6iTeSFGHL4flj58= Xref: csiph.com comp.lang.python:82477 KK Sasa writes: > Hi there, > > The list comprehension is results = [d2(t[k]) for k in > xrange(1000)], where d2 is a function returning a list, say > [x1,x2,x3,x4] for one example. So "results" is a list consisting of > 1000 lists, each of length four. Here, what I want to get is the sum > of 1000 lists, and then the result is a list of length four. Is > there any efficient way to do this? Because I found it is slow in my > case. I tried sum(d2(t[k]) for k in xrange(1000)), but it returned > error: TypeError: unsupported operand type(s) for +: 'int' and > 'list'. Thanks. Why didn't you follow Mark Lawrence's advice? In your problem, results is a list of N sublists, each containing exactly four numerical values, Let's try with N=2 In [36]: results = [d2(t[k]) for k in range(2)] In [37]: print results [[1, 2, 3, 4], [5, 6, 7, 8]] Let's try the obvious method to sum In [38]: [sum(el) for el in results] Out[38]: [10, 26] not what you're looking for, but what if we had In [39]: [sum(el) for el in zip(*results)] Out[39]: [6, 8, 10, 12] correct. BTW, as you're using the scientific stack the answer of Christian Gollwitzer is the more appropriate.