# How do you drop items in a list that's created through a loop?

I have the following lines of code:

randomnumbers = {10};
For[w = 1, w <= 10, w++,
randomnumbers = Append[randomnumbers, RandomInteger[10]];
addition = Last[randomnumbers] + Last[Drop[randomnumbers, -1]];

Print[randomnumbers];
]


Basically, I have a list given by randomnumberswhere the first number is 10. Every iteration of the loop adds a random integer between 0 - 10 to randomnumbers. Once that number is added, I then do addition and I add the newly appended number to the number immediately before it. The issue is that every time the loop runs, randomnumbersstores all the previously added values. What I would like to do is that once additionis performed, the number in position 1 of randomnumbers is dropped. That way at any one time, there are only a max of two numbers in the list made by randomnumbers the newly appended number and the one immediately before it.

As it currently runs the outputs look something like this:

{10,1}
11
{10,1,2}
3
{10,1,2,5}
7
etc


but I would like an output that runs like what I've written below, where the list is not continuously increasing.

{10,1}
11
{1,2}
3
{2,5}
7
etc


I have tried adding in Drop[randomnumbers,1]after addition, but that doesn't seem to continuously remove the number in position 1 of randomnumbers

• Have you tried randomnumbers = Drop[randomnumbers,1]? Jul 29, 2020 at 20:03

randomnumbers = {10};
For[w = 1, w <= 10, w++,
randomnumbers = {Last[randomnumbers], RandomInteger[10]};
Print[randomnumbers];

• Wow, that's neat! Jul 30, 2020 at 3:02

The answer you are looking for is this one:

randomnumbers = {10};
For[w = 1, w <= 10, w++,
If[w > 1, randomnumbers = Drop[randomnumbers, 1];
randomnumbers = Append[randomnumbers, RandomInteger[10]];,
randomnumbers = Append[randomnumbers, RandomInteger[10]];];
addition = Last[randomnumbers] + Last[Drop[randomnumbers, -1]];


P.S. I don't know yet how to properly write a code as an answer, I apologize for that, it is my second day using StackExchange forums.

Note you could this with NestList, e.g.

fun[n_] :=
With[{s = Rest[NestList[{#[[2]], RandomInteger[10]} &, {0, 10}, n]]},


A list of 10 fun[10]:

{{{10, 0}, 10}, {{0, 7}, 7}, {{7, 6}, 13}, {{6, 1}, 7}, {{1, 7},
8}, {{7, 6}, 13}, {{6, 6}, 12}, {{6, 10}, 16}, {{10, 10}, 20}, {{10, 3}, 13}}