# Operate on several lists to create one list

How do you put corresponding values from different lists together according to some operation?

E.g. I have three lists giving the velocity in the x, y and z direction respectively. I'd like create one list giving the 2-norm, $\sqrt{x^2+y^2+z^2}$.

I would be able to do it procedurally by using for example MapIndexed on one of the lists toghether with Part, I suppose. But I'd like to know if there is a more elegant solution.

• I believe you will find this Q/A informative. – Mr.Wizard Mar 17 '12 at 13:04

The general way to do this is using MapThread. Using your norm example,

MapThread[Norm[{##}]&, {listX, listY, listZ}]


This particular example has easier solutions though:

Sqrt[ listX^2 + listY^2 + listZ^2 ]

• I can't test in Mma at the moment, but I belive this is correct. – Szabolcs Mar 17 '12 at 12:55
• Looks right to me. – Mr.Wizard Mar 17 '12 at 13:01

Map on the Transposed list seems to be faster than MapThread

Map[Norm,Transpose@{listX, listY, listZ}]


but not nearly as fast as Szabolcs's second suggestion Sqrt[listX^2+listY^2+ listZ^2].

• Your method Norm/@ Transpose@{X, Y, Z} is faster than Szabolcs' firt one, and more general than his second one, since you can use e.g. Norm[#,p]& where p is a real number >=1, however in this case not much faster than the first one. – Artes Mar 17 '12 at 16:47
• @Artes, good observation. Didn't think about other norms, but noticed that Norm[#,2]& and Norm gave roughly the same timings. More interestingly, Total[{X,Y,Z}] is about 10X faster than Norm[#,1]&/@Transpose@{X,Y,Z}] (roughly same improvement in the Sqrt[X^2+Y^2+Z^2] versus Norm/@Transpose@{X,Y,Z} comparison.) – kglr Mar 18 '12 at 1:38
• Norm[#,2]& and Norm are equivalent, so it's not surprising they give the same timings, while Norm[#,1]&/@Transpose@{X,Y,Z}] and Total[{X,Y,Z}] are not, since you should do something like this Total@Abs@{X, Y, Z}, but I think even in this case the latter way would be faster, but haven't checked it. – Artes Mar 18 '12 at 13:40