I want to apply Length
in each element from a list. For example:
My list is: {1,{2,3},{4,5,6}}
How to apply Length
in each element of this list?
Length[{1}]
Length[{2,3}]
Length[{4,5,6}]
I have tried to use Thread
, but doesn't works:
In[235]:= Thread[Length[{1, {2, 3}, {4, 5, 6}}]]
Out[235]= 3
The result that I want is some like:
1
2
3
Which is the number of elements in each element.
Answer
If[AtomQ @ #, 1, Length @ #] & /@ {1, {2, 3}, {4, 5, 6}}
{1, 2, 3}
If the input list does not contain {}
(thanks: @corey979), you can also use:
Length /@ {1, {2, 3}, {4, 5, 6}} /. 0 -> 1
(* or Map[Length]@{1, {2, 3}, {4, 5, 6}} /. 0 -> 1 *)
{1, 2, 3}
Comments
Post a Comment