What use of 'sum' in this line code?

Steven D'Aprano steve at pearwood.info
Sun Jan 3 19:43:41 EST 2016


On Mon, 4 Jan 2016 11:28 am, Robert wrote:

> Hi,
> 
> I find below code snippet on line:
> 
> 
> //////////
> m = 10
> theta_A = 0.8
> theta_B = 0.3
> theta_0 = [theta_A, theta_B]
> 
> coin_A = bernoulli(theta_A)
> coin_B = bernoulli(theta_B)
> 
> xs = map(sum, [coin_A.rvs(m), coin_A.rvs(m), coin_B.rvs(m), coin_A.rvs(m),
> coin_B.rvs(m)]) /////////
> 
> I see
> [coin_A.rvs(m), coin_A.rvs(m), coin_B.rvs(m), coin_A.rvs(m),
> [coin_B.rvs(m)]
> 
> is simply a list, 


A list of what? Without knowing what coin_A.rvs(m) returns, it is impossible
to know what sum will do.



> but I don't know what use of 'sum' in this line. 
> I replace the random number with a simple list:
> ///////
> yy=map(sum, [13, 22, 33, 41])

> In [24]: yy 
> Out[24]: [13, 22, 33, 41]

I do not get that result. I get an error:


py> yy = map(sum, [13, 22, 33, 41])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable




Try replacing the list-of-mystery-things with a list of lists:


map(sum, [[1, 2, 3], [4, 5, 6], [7, 8, 9]])

and see what you get.



-- 
Steven




More information about the Python-list mailing list