3

In Jupyter notebook, is there any way to re-use the output the line above, within a cell?

Coming from Mathematica, I often find it useful to write things commands which work on the output of the last line using %, here's a stupid example:

Integrate[f[x],x]
Limit[%,x->1] - Limit[%,x->0] 

In general one can write %%% for 3rd-last output etc. https://reference.wolfram.com/language/ref/Out.html

@nostradamus reminds me that underscore _ is the output of the last cell, at least in Python. (Get last answer .) I didn't initially ask this, but would particularly like to be able to do this within a cell, so as to be able to execute multiple steps with one shift-enter.

I would also like to know if there's a way of doing either of these in Julia instead of Python.

improbable
  • 306
  • 2
  • 7
  • Things I found which don't quite help: * How to print all outputs: https://stackoverflow.com/a/36835741/8187364 * A package which supports Out(n): https://github.com/jlapeyre/Symata.jl – improbable Jun 20 '17 at 08:57
  • Please check [this](https://stackoverflow.com/questions/200020/get-last-answer). Possible duplicate. – nostradamus Jun 20 '17 at 09:04
  • Thanks, I did not know that. Am I correct in thinking that `_` always uses cell output, not the output of lines within a cell? I will update my question a bit if that is OK... – improbable Jun 20 '17 at 09:15
  • I think you are correct, although I do not understand what you mean by "not the output of lines within a cell". Whereas `_` will use the previous output, you can reference to any output cell using `_x`, which is an abbreviation for `Out[x]`. Furthermore, `___` works as well (as `%%%` in Mathematica). See e.g. [here](https://www.safaribooksonline.com/library/view/python-data-science/9781491912126/ch01.html) "Input and Output History". – nostradamus Jun 20 '17 at 09:19

3 Answers3

4

In julia, ans stores the result of evaluating the last statement.

4*2
ans/2

You may also be interested in checking out the piping syntax

4*2 |>
sqrt
Michael K. Borregaard
  • 7,864
  • 1
  • 28
  • 35
  • 1
    Thanks, I should have found`ans` (also here, I now see: https://stackoverflow.com/questions/33192955/does-julia-have-something-equivalent-to-ans-matlab-or-last-value-r ) but never thought to look for pipe. – improbable Jun 20 '17 at 11:16
4

You can use "_" and works generally in python environment.

enter image description here

ozw1z5rd
  • 3,034
  • 3
  • 32
  • 49
0

In case someone else finds this with google, I just discovered a package that does roughly what I wanted, in Julia: ChainRecursive.jl uses it as the magic word, like so:

julia> using ChainRecursive

julia> @chain for k=1:4
           k^2 + k^3
           print(" $k -> $it ")
       end

 1 -> 2  2 -> 12  3 -> 36  4 -> 80

There appears to be no performance lost by using this, as it is un-wrapped before compilation.

improbable
  • 306
  • 2
  • 7