Question

In an IPython notebook I input this code in a cell:

from IPython.display import HTML
HTML("""<div>One</div>""")
HTML("""<div>Two</div>""")

How come the output cell only contains the second div?

EDIT. @Dunno has shown how I can put all the html into one HTML() and both elements are rendered, but I still don't understand what's going on. Here's a more general case:

When I enter this in an input cell:

1
2
3

The output is

3

But if I enter the following:

print 1
print 2
print 3

Then I get this output:

1
2
3

What's the difference? Is IPython notebook only evaluating the last statement when I don't use print statements? Or is each subsequent evaluation overwriting the previous one?

Was it helpful?

Solution

Yeah I found some documentation on this, and HTML is actually a class, not a function.

So the correct code would be

from IPython.display import HTML
myhtml = HTML("""<div>One</div><div>Two</div>""") #make the html object
myhtml #display it

Now it makes sense why your code displays only one div.

To display multiple parts create multiple variables, containing the html and then concatenate them inside one call to HTML.

div1 = """<div>One</div>"""
div2 = """<div>Two</div>"""
myhtml = HTML(div1 + div2)
myhtml

Edit:

I opened a ticket on ipython's github profile to see if it's a bug or a feature that only the last line of statements is displayed. Turns out, it's planned behaviour:

quoting Thomas Kluyver:

This is deliberate, because if you call something in a for loop that returns a value:

for line in lines:
    f.write(line)  # Returns number of bytes written

You probably don't want to see all those numbers in the output.

The rule in IPython is: if the last statement in your code is an expression, we display its >value. 1;2 is a pair of statements, whereas 1,2 is one statement, so both values will >display.

I hope that explains things a bit. We're happy to revisit decisions like this, but it's >been this way for years, and I don't think anyone has taken issue with it.

OTHER TIPS

Just a small addition to @Dunno's answer: if you want to display multiple IPython.display.DisplayObject objects (this includes HTML objects but also images etc.) from a single cell, you can use the IPython.display.display function.

For example, you can do:

from IPython.display import HTML, Image, display
display(HTML("""<div>One</div>"""))
display(HTML("""<div>Two</div>"""))
display(Image("http://cdn.sstatic.net/stackoverflow/company/img/logos/so/so-logo.png?v=9c558ec15d8a", format="png"))

Output of the above code

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top