# Creating a function that is a variant of Length [closed]

I want to create a new function nLength that applies Lengthin each element from a list automatically. For example:

I have a list: {1,{2,3},{4,5,6}}

If I use nLengthhas to return:

nLength[{1,{2,3},{4,5,6}}]

{1,2,3}


Which is the number of elements in each element.

I have tried some like that, but doesn't works:

nLength[{n__}] := Map[Length, #]&n

• Possible duplicate of How to apply Length in all elements Commented Jan 22, 2019 at 18:50
• Is not the same question. Now I want to create a new function using a pure function. Some in syntax (I guess) is wrong and I don't know where. Commented Jan 22, 2019 at 18:55
• nLength[{n__}] := Map[Length[#] &, {n}] is what you're looking for. By the way the first element is not a list, so it's length is 0. Commented Jan 22, 2019 at 19:13
• Wouldn't it be clearer and fewer keystrokes to avoid defining a new function and use Length/@{1, {1, 2}, {1, 2, 3}} since all the function does is call the built-in Length function? Commented Jan 22, 2019 at 19:29
• Why is Length[1] == 1?
– Kuba
Commented Jan 22, 2019 at 19:53

I can think of no good reason for using a pure function in the implementation of your variant of List, but I do think your requirement that atoms should be treated as having length 1 is something that requires some thought.

Here is how I would do it.

Clear[helper, nLen]
helper[item_?AtomQ] := 1
helper[item_] := Length[item]
nLen[u_ /; Length[u] === 0] := 0
nLen[u_] := helper /@ u


Now some tests including looking at some edge cases.

nLen[{1, {2, 3}, {4, 5, 6}}]


{1, 2, 3}

nLen[foo[{}, {1}, bar[2, 3], quux[4, {a, b}, {}]]]


foo[0, 1, 2, 3]

nLen[{}]


0

nLen[f[]]


0

Note that like Length, nLen works on expression with any head.

ClearAll[lENGTH]
lENGTH = Module[{s = 0}, ++s & /@ Map[List, Inactivate @ #, {-1}]; s] &;


Examples:

Grid[Prepend[{#, lENGTH@#, Length@#} & /@ {3, a, {}, {{}}, f[], a + b, a b c,
f[1, aa, b, 3], {1, 2}, {1, 2, 3},{1, {2, {3, {4, {5}}}}},
<|a -> 1, b -> 2|>, SparseArray[{{1, 1} -> 1, {10, 3} -> 2}], Rational[x, 3], y^4},
{"expr", "lENGTH @ expr", "Length @ expr"}], Dividers -> All]