# An alternative to (%%…%) (k times) [closed]

Sometimes it may be useful to use (%%…%) (k times) to get the kth previous result in a notebook instead of setting a variable.

However, if I want to get the 8th previous result, for example, I would have to type (%) eight times (%%%%%%%%) and I could get lost. Needless to remember that every time (%) is needed (Shift)(5) must be pressed, which demands both hands and is somewhat inconvenient.

So, in the code below, I have defined a new command.

Now, when I want the previous 4th result I just type (o4) instead of (%%%%). If I wanted a previous result before the 9th, say the 14th, I would have to change the Range in the command to Range and generate (o1…o14). I could also obtain only the previous 3rd to the 7th values using Range[3, 7], getting (o3…o7).

This command should be run every time a new session of Mathematica is initiated. It could be written in an initialization cell in the notebook. Remember that you should not redefine or clear (o1…o9) at the cost of getting unexpected errors. You must consider them as "system variables".

(* Define o1,o2,...,o9 as "%","%%",...,"%%%%%%%%%" *)
Map[ToExpression[StringJoin["o", ToString[#], " := ", "Out[\$Line - ", ToString[#], "]"]] &, Range];


Example:

Pi/6.
{Sin[%], Sin[o1]}
{Cos[%%], Cos[o2]}
{Tan[%%%], Tan[o3]}
{Sin[2 %%%%], Sin[2 o4]}
{Cos[2 %%%%%], Cos[2 o5]}
{Tan[2 %%%%%%], Tan[2 o6]}

0.523599
{0.5, 0.5}
{0.866025, 0.866025}
{0.57735, 0.57735}
{0.866025, 0.866025}
{0.5, 0.5}
{1.73205, 1.73205}

• Just use Out. See the "Details" section. – Alan Sep 25 '19 at 19:15
• As in Out[-5] (i.e., five lines ago). Though frankly, in such a situation, I would start with foo = Pi/6. and then use foo instead of % or Out. – Michael E2 Sep 25 '19 at 19:19
• Maybe try With[ { foo = Pi/6 }, { {Sin[ foo ], Sin[ o1 ]}, ... } ] and use Column to arrange the output. – LouisB Sep 25 '19 at 19:31
• Out[-k] is not as convenient as the command presented. What I wanted to show is a simpler form of getting previous values writing only o1, o2 &c, with only 2 keystrokes instead of having to use 8 keystrokes every time I use Out[-k] or (k +1) keystrokes when I use (%). – Caio Sep 25 '19 at 21:19

% is just a shorthand for Out[-1] or even Out[]. And so on, Out[-k] gives the k-th previous result. Or from the details section of Out

Out[-k] is equivalent to %%...% (k times).

One way I've used Out, along with the way you can get multiple outputs by giving it a list of negative integers, before is testing timing and equality between different methods.

ClearSystemCache[]
Range[-10^6, 10^6]~Complement~{0} // AbsoluteTiming;
Join @@ {-Reverse@#, #} &@Range[10^6] // AbsoluteTiming;
Out[{-1, -2}][[;; , 1]]
SameQ @@ Out[{-1, -2} - 1][[;; , 2]]


{0.0201598, 0.0370587}

True

Or maybe a more clear example

a;
b;
Out[{-1, -2}]


{b, a}