# How to create a function that merges the first $n$-digits of each value in a list?

Suppose we have a list of numbers. For example,

A={1231,1232,1233,1241,1236}


Using a function f[x,A], I want to rearrange this list into a group of lists that contain the first digits (for x=1)

f[1,A]={1,2,3,1,6}


The first and second digits (for x=2)

f[2,A]={31,32,33,41,36}


The first, second, third digits (for x=3) and continuing until we cover the value in the original list with the most digits (x=Max@@ IntegerLength/@A).

(If there are zeros in the first digit, i.e 01 then the zeros must be ignored i.e 1).

How do we proceed?

• The OP can use terms such as "least significant digit" and "most significant digit" to remove this ambiguity caused by "first digit" etc. Please also mention if the numbers have the same number of digits.
– Syed
Jan 20, 2022 at 17:05

Use Mod:

f[n_, list_] := Mod[list, 10^n]


Then:

f[1, A]
f[2, A]
f[3, A]


{1, 2, 3, 1, 6}

{31, 32, 33, 41, 36}

{231, 232, 233, 241, 236}

A = {1231, 1232, 1233, 1241, 1236, 1205};

ClearAll[f]
f[i_Integer, a_List] := FromDigits[ #[[-i;;]] ]& /@ IntegerDigits[a]

f[1, A]
(* Out: {1, 2, 3, 1, 6, 5} *)

f[2, A]
(* Out: {31, 32, 33, 41, 36, 5} *)

• you can also use the 3-argument form of IntegerDigits, that is, FromDigits /@ IntegerDigits[a, 10, i]
– kglr
Jan 20, 2022 at 18:56
• @kglr That's nice! I don't think I knew that form. Thank you. Jan 20, 2022 at 20:35
f[n_, list_] := FromDigits /@ Reverse /@ (Take[#, UpTo[n]] & /@ Reverse /@ IntegerDigits /@ list)

B = {1, 12, 123, 1234, 10005}
Table[f[i, B], {i, 1, 5}]
(*
{{1, 2, 3, 4, 5},
{1, 12, 23, 34, 5},
{1, 12, 123, 234, 5},
{1, 12, 123, 1234, 5},
{1, 12, 123, 1234, 10005}}
*)

list = {1231, 1232, 1233, 1241, 236, 5};


Using string-functions

f[n_][x_] := ToExpression @ StringTake[StringPadLeft[ToString /@ x], -n]

f[3] @ list


{231, 232, 233, 241, 236, 5}

f[#] @ list & /@ Range[4] // TableForm


A = {1231, 1232, 1233, 1241, 1236};


Using TakeDrop:

f[n_Integer, A_List] /; n == 1 :=
FromDigits@*First@TakeDrop[Reverse@#, n] & /@ IntegerDigits[A]

f[n_Integer, A_List] /; n > 1 :=
FromDigits@*Reverse /@ (First@TakeDrop[Reverse@#, n] & /@ IntegerDigits[A])

Table[f[n, A], {n, 1, 4}] // TableForm


Clear["Global*"]

f[n_Integer?Positive, {m__Integer?Positive}] :=
Module[{len = Max[Ceiling[Log10[{m}]]]},
FromDigits[PadLeft[IntegerDigits[#], len][[-n ;;]]] & /@ {m}]

A = {1231, 1232, 1233, 1241, 001236, 12, 12006};

Table[f[n, A], {n, 1, Max[Ceiling[Log10[A]]]}] // Column
`