2
$\begingroup$

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.

$\endgroup$
1
  • 2
    $\begingroup$ What in your opinion is the Length of 1? You can use Map: Map[Length, {1, {2, 3}, {4, 5, 6}}]. $\endgroup$ – Carl Lange Jan 22 '19 at 17:45
7
$\begingroup$
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}

$\endgroup$
2
  • $\begingroup$ Note that the first approach fails on {1, {2, 3}, {}, {4, 5, 6}}. The second, however, works well. $\endgroup$ – corey979 Jan 22 '19 at 18:24
  • $\begingroup$ @corey979, very good point. $\endgroup$ – kglr Jan 22 '19 at 18:30
5
$\begingroup$

Introduce Charting`padList to make a list for your element..

Length@*Charting`padList /@ {1, {2, 3}, {4, 5, 6}}

{1, 2, 3}

$\endgroup$
1
  • 2
    $\begingroup$ Brilliant. Care to elaborate more on Charting`padList? $\endgroup$ – corey979 Jan 22 '19 at 18:22
0
$\begingroup$

A mildly adjusted version of the nice Charting answer by yode is to apply a list to each element and flatten:

Length@Flatten@List@#&/@{1, {2, 3}, {4, 5, 6}}
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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