3
$\begingroup$

I have learnt how to generate a sequence of numbers, but now I come across a question whether it is possible to generate e sequence of lists. Say, I would like to generate {1},{1,2},{1,2,3},...,{1,2,3,...,10}. How can I do that?

$\endgroup$
6
  • 9
    $\begingroup$ Range /@ Range[10] :-D $\endgroup$ Commented Apr 15, 2016 at 10:41
  • $\begingroup$ @JasonB: What? Hahaha... That really works. I am new in Mathematica. And haven't learnt that symbol '\@'. Could you explain? $\endgroup$ Commented Apr 15, 2016 at 10:44
  • 1
    $\begingroup$ So Range[x] will give {1, 2, 3, 4, 5,......x}, and /@ is the infix notation for Map. As an example, look f /@ {1, 2, 3} gives {f[1], f[2], f[3]}. So in the above, Range[10] gives {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, and then I'm just mapping Range onto that list $\endgroup$ Commented Apr 15, 2016 at 10:47
  • 1
    $\begingroup$ at least closely related: generate successive sublists from a list? $\endgroup$ Commented Apr 15, 2016 at 11:46
  • 1
    $\begingroup$ Or Range@Range[10]. See here under 'neat examples' $\endgroup$ Commented Apr 15, 2016 at 17:26

2 Answers 2

4
$\begingroup$

Try this:

Table[Range[i], {i, 1, 10}] (* {{1}, {1, 2}, {1, 2, 3}, {1, 2, 3, 4}, {1, 2, 3, 4, 5}, {1, 2, 3, 4, 5, 6}, {1, 2, 3, 4, 5, 6, 7}, {1, 2, 3, 4, 5, 6, 7, 8}, {1, 2, 3, 4, 5, 6, 7, 8, 9}, {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}} *) 

or this:

Table[Table[k, {k, 1, i}], {i, 1, 10}] 

with the same result. Have fun!

$\endgroup$
1
  • $\begingroup$ Yes. That generates the same result. Thanks :) $\endgroup$ Commented Apr 15, 2016 at 11:45
2
$\begingroup$

My entry into the obfuscated Mathematica competition for April, 2016.

rangeList[n_Integer?Positive] := NestList[Join[#, {Last[#] + 1}] &, {1}, n - 1] rangeList[5] 

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

Too bad I'm posting this on April 15 rather than April 1.

$\endgroup$
1
  • $\begingroup$ FoldList[(Flatten@*List), Nothing, Range[10]] == Range@Range[10] $\endgroup$ Commented Apr 15, 2016 at 17:29

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.