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}

  • $\begingroup$ 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. $\endgroup$
    – Nasser
    Sep 6, 2022 at 6:59
  • $\begingroup$ 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]]]] ] $\endgroup$ Sep 6, 2022 at 7:11
  • $\begingroup$ thanks more Daniel Binosi $\endgroup$
    – Ahmed
    Sep 6, 2022 at 7:21

2 Answers 2


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

  • $\begingroup$ I want to use loop and put results in list $\endgroup$
    – Ahmed
    Sep 6, 2022 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];


{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}


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.