tmp = {x, y, z}^{1, 2, 3}
Times @@ tmp
Length[%]
This gives a length of 3. But I was expecting 1.
What is exactly this "length" of x*y^2*z^3 called? I would think this as a scalar of length 1?
Thanks!
tmp = {x, y, z}^{1, 2, 3}
Times @@ tmp
Length[%]
This gives a length of 3. But I was expecting 1.
What is exactly this "length" of x*y^2*z^3 called? I would think this as a scalar of length 1?
Thanks!
According to the documentation:
Length[expr]
gives the number of elements in expr.
in your case
tmp = {x, y, z}^{1, 2, 3}
r=Times @@ tmp
(*x y^2 z^3*)
r is an expression with thee elements. to see this you do:
FullForm[r]
(*Times[x, Power[y, 2], Power[z, 3]]*)
the expression here is Times and the elements of Times are 3 (x, Power[y, 2], and Power[z, 3])
The Length operator will operate on lists, but if your object is not a list, it is not automatically considered to be length 1. When you apply Times@@ to your tmp, it is no longer a list.
Length will apply to many other expressions. For example:
Length[p+q+r]
(*Output: 3*)
Length[a*b+c]
(*Output: 2*)
Length[5+2]
(*Output: 0*)
In the first case, the sum has three parts, so it is a sum of length three. Note that if you did Length[List@@(p+q+r)] you'd get 3 also.
The next one is only length 2 because the "outermost" operation has length 2. It is a sum of two things. You can even do something like (a*b+c)[[1]] or even Length[(a*b+c)[[1]]].
The last one will produce 7 before attempting to evaluate Length, and because 7 is an "atomic" thing (it is not a list or other compound expression like a symbolic sum, product, etc.) it returns length 0.
Or try:
tmp2 = Times @@ tmp
Map[Length, List @@ tmp2]
Note that you are required to List@@ the expression. I don't think Map will map itself over products or sums, so you have to convert tmp2 back to a list, which would be {x,y^2,z^3}. Notice that x is not a compound expression so it has 0 length, just like 7.
Map will operate over non-lists. For example, Map[f, Times[a, b, c]] gives Times[f[a],f[b],f[c]].
– evanb
Nov 25 '14 at 19:32
Map[Length, tmp2] will still return 0 as expected.
– Kellen Myers
Nov 25 '14 at 19:47
f[1,2] is, unless f is defined elsewhere, going to be seen the same as any full form expression like Times[x,y] or the original expression in the question. Just like I said. If f is defined, f will be evaluated first, and the length of the resulting expression will depend entirely on what f gives with those inputs.
– Kellen Myers
Nov 25 '14 at 20:57
ClearAll[f];Length[f[1,2]] returns 2. Meanwhile ClearAll[f];f[p_,q_]=p+q;Length[f[1,2]] returns 0, while ClearAll[f,x];f[p_,q_]=p+q+x;Length[f[1,2]] returns 2.
– Kellen Myers
Nov 25 '14 at 21:25
f.
– Kuba
Nov 25 '14 at 21:25
Times @@ tmp // FullForm. Take a closer look at documentation ofLengthtoo. – Kuba Nov 25 '14 at 19:11