5
$\begingroup$

Nest[f,x,3] = f[f[f[x]]] But I want something like Fn[f,x,3] = f[f[f[x],x],x]. I think there exist some function to do that. Actually I need to copy a list $n$ times and Join with itself. So I will use

lst = {a,b,c}
Fn[Join, lst, 3] = Join[Join[Join[lst], lst], lst] = {a, b, c, a, b, c, a, b, c}

I assume something like this Fn already exist in Mathematica. But I am not sure. Is there any other way to simply duplicate a list and concatenate with itself $n$ times ?

$\endgroup$
7
$\begingroup$
Nest[f[#, x] &, f[x], 2]

Redefine the function you're nesting slightly so that it includes the extension.

Alternatively, to solve the problem you're asking for (concatenating a list to itself several times), Flatten the first layer of a ConstantArray:

Flatten[ConstantArray[list, 3], 1]
$\endgroup$
  • $\begingroup$ Thanks Join can also be used in place of Flatten[ , 1]. One extra argument. I was missing the ConstantArray function $\endgroup$ – Neel Basu Apr 6 '18 at 20:21
9
$\begingroup$
Fold[f, ConstantArray[x, 3 + 1]]

For duplicating lists, usually the following is surprisingly fast:

Flatten[{lst}[[ConstantArray[1, 3]]]]
$\endgroup$
8
$\begingroup$

Is there any other way to simply duplicate a list and concatenate with itself n times ?

Many ways. Here are two:

Flatten[Table[lst, 3]]
Join @@ Table[lst, 3]
$\endgroup$
  • $\begingroup$ I think second one is better. if the lst is a matrix then it works. However for the first one an extra argument 1 is required. $\endgroup$ – Neel Basu Apr 6 '18 at 20:19

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.