# How i calculate mean for list using for loop?

Here I hava a nested list as follow

a = {{1, 2, 3},{2, 1,2},{1, 3, 2}};

For[i = 1, i < Length[a], i++, t=Mean[a[[i]]]]


But the result is not expected I get 2 But I want {2,5/2,2}

• I want to use loop and put results in list this is what @tueda solution does. If you must use a loop, you can do First@Last@Reap[Do[Sow[Mean[a[[n]]]],{n,1,Length@a}]] but I think Map[Mean,a] is much better and more clear. (which is another way to write Mean /@ a. The reason your loop did not work is because you were overwriting t each time in the loop, and only the last value of t survived. Sep 6 at 6:59
• Very down to earth way of doing it (wrong from the point of view of MMA coding) t = {}; For[i = 1, i <= Length[a], i++, AppendTo[t, Mean[a[[i]]]] ] Sep 6 at 7:11
• thanks more Daniel Binosi Sep 6 at 7:21

Do you mean you want {2,5/3,2}? This can be obtained by Mean /@ a.

• I want to use loop and put results in list Sep 6 at 6:16

Rule number one of WL: forget that For exists. It's never a good way to do things in Mathamatica. This is what you want to do:

a = {{1, 2, 3},{2, 1,2},{1, 3, 2}};
t = Map[Mean, a];

t


{2, 5/3, 2}

If you want a more general method for computing the mean of rows/columns, look at ArrayReduce:

ArrayReduce[Mean, a, 1] (* average over rows, giving you column means *)
ArrayReduce[Mean, a, 2] (* average over columns, giving you row means *)


{4/3, 2, 7/3}

{2, 5/3, 2}