7
$\begingroup$

I would like to split a list into overlapping sublists! I want to generate a first sublist with a specified number of elements. Then I want to shift one element to the right and generate an overlapping sublist. ... and so on, until the end. All sublists should have the same length. Just as an example:

{1, 6, 3, 6, 8, 5, 3}

I would like to obtain the following:

{{1, 6, 3, 6}, {6, 3, 6, 8}, {3, 6, 8, 5}, {6, 8, 5, 3}}

I have no idea how to tackle the problem. Thanks in advance.

$\endgroup$
2
  • $\begingroup$ The first sublist here has length 4, and the others have length 5. Are you sure you meant that? $\endgroup$ Aug 18, 2015 at 14:13
  • $\begingroup$ I corrected the question! You are right. $\endgroup$
    – Niki
    Aug 18, 2015 at 14:16

1 Answer 1

8
$\begingroup$
Partition[{1, 6, 3, 6, 8, 5, 3}, 4, 1]

is probably what you want. It returns:

{{1, 6, 3, 6}, {6, 3, 6, 8}, {3, 6, 8, 5}, {6, 8, 5, 3}}
$\endgroup$
4
  • 1
    $\begingroup$ Thanks! I am a bit embarrassed that I didn't figure that out myself. $\endgroup$
    – Niki
    Aug 18, 2015 at 14:16
  • 4
    $\begingroup$ These things are obvious when you know the answer. $\endgroup$ Aug 18, 2015 at 14:17
  • $\begingroup$ I mean it was written in the documentation. I just misunderstood what is said there. Thanks anyway. $\endgroup$
    – Niki
    Aug 18, 2015 at 14:21
  • $\begingroup$ @Niki, Could I just nudge you to accept this answer, if it's all sorted? I don't like seeing those horrible grey squares in my "answers" list on my user page :P $\endgroup$ Aug 21, 2015 at 11:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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