5
$\begingroup$

I wonder if it's possible to create a list with Table from entries of the list itself. That is, as I'm creating the list, I append a new element as a function of previously added elements, in a "recursive" way.

For example, the following code does what I mean

lt = {1};
For[i = 2, i <= 5, i++, lt = Append[lt, lt[[i - 1]] + 1]];
lt

giving {1, 2, 3, 4, 5}. I wonder if the same can be achieved with Table. I naively tried

lt = {1};
lt = Table[lt[[i - 1]] + 1, {i, 2, 5}]

which unsurprisingly doesn't work. Maybe there is an alternative to this that avoids using For and Append. I've heard of RecurrenceTable, but I'm not entirely sure how it works.

Any ideas?

$\endgroup$
1
  • 8
    $\begingroup$ Try NestList, or NestWhileList in case when you need access to more than one previous element. In your case, it would be NestList[# + 1 &, 1, 4]. You can also use simple Nest even when you need access to previous results, by collecting them in a (sub)list. Here is for example a way to compute Fibonacci numbers: NestList[{Last@ #, Total[#]} &, {1, 1}, 10][[All, 1]]. Also, Nest auto-compiles, so this method can be reasonably fast if the nesting function is compilable $\endgroup$ Jan 9, 2020 at 13:14

2 Answers 2

10
$\begingroup$

In my opinion, NestList is the most direct answer to the question in the OP, i.e. to "create a list from entries of the list itself", as Leonid suggested as well. The simple example in the OP then becomes:

NestList[# + 1 &, 1, 4]

{1, 2, 3, 4, 5}

NestWhileList allows a function to run until a certain condition is met, in those cases in which the number of iterations is not known a priori:

NestWhileList[# + 2 &, 1, # < 20 &]

{1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21}

I mention this example specifically because it highlights a behavior that trips me up from time to time: the generated item that finally falsified the condition is included in the results. This is the first point in the Details section of the docs for this function. Of course Most@NestWhileList[...] can be used to remove that last item, if needed.

The tutorial on Applying Functions Repeatedly might be of interest as well.

$\endgroup$
7
$\begingroup$

Use RecurrenceTable or RSolve

Clear["Global`*"]

Clear[lt]

RecurrenceTable[{lt[n + 1] == lt[n] + 1, lt[1] == 1}, lt, {n, 1, 5}]

(* {1, 2, 3, 4, 5} *)

Or find a general term of the table

sol = RSolve[{lt[n + 1] == lt[n] + 1, lt[1] == 1}, lt, n][[1]]

(* {lt -> Function[{n}, n]} *)

Verifying that the solution satisfies the equations

{lt[n + 1] == lt[n] + 1, lt[1] == 1} /. sol

(* {True, True} *)

Generating a table from the general solution

lt /@ Range[5] /. sol

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

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.