Novice
Novice

Reputation: 575

Jupyter Notebook different ways to display out

There seems to be 3 ways to display output in Jupyter:

  1. By using print
  2. By using display
  3. By just writing the variable name

What is the exact difference, especially between number 2 and 3?

Upvotes: 2

Views: 6940

Answers (2)

CrepeGoat
CrepeGoat

Reputation: 2515

Here's my understanding:

  1. print is just the native print function that Python provides, as defined here in the Python docs.

    in short, it'll spit out a text representation of whatever you put in, and put that in the cell's output. but that's it; it only does text.

  2. display is IPython's special-sauce function (see the ipython docs). it's a lot like print, in that 1. you put stuff in and 2. it'll put a representation of the stuff in the cell's output.

    The difference from print is that display can make representations that are WAY more than "just text" (as @Alex Yu noted, "markdown, HTML, video, images, audio", etc.). All the different types of media that display can support are described in the IPython docs linked above as well.

  3. "just writing the variable name", specifically on the last line of a cell, will just call display on that variable name under the hood. I.e., it's just a short-hand convenience. (Though I can't find any docs confirming this; any links appreciated!)

Upvotes: 2

hpaulj
hpaulj

Reputation: 231385

I haven't used display, but it looks like it provides a lot of controls. print, of course, is the standard Python function, with its own possible parameters.

But lets look at a simple numpy array in Ipython console session:

Simply giving the name - the default out:

In [164]: arr
Out[164]: array(['a', 'bcd', 'ef'], dtype='<U3')

This is the same as the repr output for this object:

In [165]: repr(arr)
Out[165]: "array(['a', 'bcd', 'ef'], dtype='<U3')"
In [166]: print(repr(arr))
array(['a', 'bcd', 'ef'], dtype='<U3')

Looks like the default display is the same:

In [167]: display(arr)
array(['a', 'bcd', 'ef'], dtype='<U3')

print on the other hand shows, as a default, the str of the object:

In [168]: str(arr)
Out[168]: "['a' 'bcd' 'ef']"
In [169]: print(arr)
['a' 'bcd' 'ef']

So at least for a simple case like this the key difference is between the repr and str of the object. Another difference is which actions produce an Out, and which don't. Out[164] is an array. Out[165] (and 168) are strings. print and display display, but don't put anything on the Out list (in other words they return None).

display can return a 'display' object, but I won't get into that here. You can read the docs as well as I can.

Upvotes: 3

Related Questions