# Please explain the following code containing Partition and Flatten

I'm a beginner in Mathematica. I have the following code:

A = NestList[func, x0, n];
B = Partition[Flatten[{#, #, #, #} & /@ A][[2 ;; -2]], 2]


I don't understand the meaning of the syntax for B. What exactly is happening there (could someone explain this in words?). How could one understand the interval directly after the Flatten function and what is it addressing?

• What about evaluating this step by step? {#, #, #, #} & /@ A then Flatten[%] etc? – Kuba Feb 14 '18 at 19:55
• This is a Great tip. Tried it out and now i‘m wondering why i didn‘t do this in the first place ✌️ – JtSpKg Feb 15 '18 at 10:27

Let's look at it from the inside out, starting with

{#,#,#,#} &


This is a nameless function which takes any input and returns a list containing that input 4 times by directly repeating its argument.

{#,#,#,#} & /@ A


This Maps (/@ is a shorthand infix for Map) the nameless function over every member of A. This returns a list containing lists of 4 copies for every member of A.

Flatten[{#,#,#,#} & /@ A]


This flattens that list of lists back into a normal list, effectively creating a 1D list repeating each element of A 4 times in the same order that A has them.

Flatten[{#,#,#,#} & /@ A][[2 ;; -2]]


This then takes the second through second to last members of that list, discarding the very first and the very last elements.

Partition[Flatten[{#,#,#,#} & /@ A][[2 ;; -2]], 2]


Finally this breaks the list into non-overlapping pairs, starting from the beginning.

• Thanks a lot for this clear explanation. In the Future i will try to decompose new confusing code similarly. – JtSpKg Feb 15 '18 at 10:24