2
$\begingroup$

This question already has an answer here:

For example, I would like to partition {1,2,3,4,5} into

{1}
{1,2}
{1,2,3}
{1,2,3,4}
{1,2,3,4,5}

with just one line of code. Is there any way to do this? I am working with a much larger data set and do not want to have to separate the list into shorter and shorter lists manually. Thank you for your help.

$\endgroup$

marked as duplicate by Mr.Wizard list-manipulation Jan 29 '16 at 0:18

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

4
$\begingroup$
FoldList[Join, List /@ {1, 2, 3, 4, 5}]
$\endgroup$
4
$\begingroup$
myList = {1, 2, 3, 4, 5};
Reverse@NestList[Most, myList, Length[myList]-1]

Of the four solutions posted, this one is the fastest on large sets. Using Timing and the data set Range[10^3], the execution times are:

  • Table[Take[list, i], {i, Length[list]}] 0.00351 seconds
  • Reverse@NestList[Most, myList, Length[myList]-1] 0.002089 seconds
  • FoldList[Join, List /@ Range[10^3]] 0.002965 seconds
  • x[[;; #]] & /@ Range@Length@x 0.002537 seconds
$\endgroup$
2
$\begingroup$
list={1,2,3,4,5};
Table[Take[list, i], {i, Length[list]}]

will give you

{{1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}}
$\endgroup$
1
$\begingroup$
x = {1, 2, 3, 4, 5};
x[[;; #]] & /@ Range@Length@x

(* {{1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}} *)
$\endgroup$

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