The display() function from IPython's rich display system renders interactive, formatted representations of objects—including HTML tables, styled Pandas DataFrames, Markdown text, LaTeX math equations, images, and audio—directly within notebook cells in Jupyter, VS Code, and Google Colab.
Standard Python Equivalent: In traditional terminal scripts, output is restricted to plain text via print(). In notebook environments, display() unlocks the frontend browser rendering engine for interactive data visualization.
In Jupyter and Google Colab, display() is built directly into the global interactive namespace. In standalone scripts or modules, import it from IPython.display:
from IPython.display import display
display(*objs, include=None, exclude=None, metadata=None, transient=None, display_id=None, **kwargs)
| Parameter | Type | Default | Description |
|---|---|---|---|
*objs |
Any |
(Required) | One or more Python objects to render (e.g. DataFrames, HTML, strings, plots). |
include |
list or set |
None |
MIME types to include when selecting representations (e.g. ['text/html', 'image/png']). |
exclude |
list or set |
None |
MIME types to explicitly filter out from display. |
metadata |
dict |
None |
Metadata dictionary passed to frontend renderers (e.g. image dimensions or CSS classes). |
display_id |
bool or str |
None |
If set to True or a custom string ID, returns a DisplayHandle for live in-place updating of the rendered output. |
While both functions output information, their underlying mechanisms and rendered formats are fundamentally different:
| Feature | print() |
display() |
|---|---|---|
| Output Target | Standard Output stream (sys.stdout) |
IPython display publisher / notebook frontend |
| Format | Plain text (converts via __str__) |
Rich MIME bundle (HTML, SVG, PNG, Markdown, JSON) |
| Multiple Outputs | Outputs plain text lines sequentially | Can render multiple rich widgets, tables, and charts across a single cell |
| DataFrames | Plain monospace text table | Interactive scrollable HTML table with zebra striping |
In notebook environments, typing a DataFrame variable name only renders the table if it is on the final line of the cell. Using display() allows you to output multiple DataFrames at any stage of your data analysis pipeline:
import pandas as pd
from IPython.display import display
df1 = pd.DataFrame({
"Name": ["Alice", "Bob"],
"Score": [92, 88]
})
df2 = pd.DataFrame({
"Name": ["Charlie", "Diana"],
"Score": [95, 79]
})
print("--- Raw Text (print) ---")
print(df1)
print("--- Rich Table (display) ---")
display(df1)
display(df2)
print(df1) prints monospace ASCII lines.
display(df1) and display(df2) render clean HTML tables with interactive column headers and hover states inside the notebook output area.
IPython provides specialized wrapper classes that inform display() how to render non-text data:
from IPython.display import display, HTML, Markdown, Math
# 1. Styled HTML banner
html_banner = HTML("""
<div style='background-color:#e8f4fd; border-left:4px solid #1a73e8; padding:10px;'>
<strong style='color:#1a73e8;'>Notice:</strong> Model training completed successfully!
</div>
""")
display(html_banner)
# 2. Dynamic Markdown with bullet points
md_content = Markdown("""
### Execution Summary
* **Accuracy:** 96.4%
* **Loss:** 0.082
* **Status:** Ready for deployment
""")
display(md_content)
# 3. Mathematical Formula (LaTeX)
formula = Math(r"E = mc^2 \quad ext{and} \quad \sigma = \sqrt{rac{1}{N}\sum_{i=1}^N (x_i - \mu)^2}")
display(formula)
One of the most powerful features of display() is the ability to update existing cell output in place without printing hundreds of repetitive lines. Setting display_id=True returns a DisplayHandle object with an update() method:
import time
from IPython.display import display, HTML
# Create a handle by setting display_id=True
handle = display(HTML("<b>Progress: 0%</b>"), display_id=True)
for step in range(1, 5):
time.sleep(0.3)
pct = step * 25
# Overwrites the existing element in-place
handle.update(HTML(f"<b>Progress: {pct}% completed</b>"))
You can make your own Python classes render as rich HTML components by defining the special method _repr_html_(self). When passed to display(), IPython automatically invokes this method:
class MetricBadge:
def __init__(self, label, value, change_pct):
self.label = label
self.value = value
self.change_pct = change_pct
def _repr_html_(self):
color = "#0b8043" if self.change_pct >= 0 else "#d93025"
symbol = "+" if self.change_pct >= 0 else ""
return (
f"<div style='padding:8px 12px; border:1px solid #ccc; border-radius:6px; display:inline-block;'>"
f" <strong>{self.label}:</strong> {self.value} "
f" <span style='color:{color}; font-weight:bold;'>({symbol}{self.change_pct}%)</span>"
f"</div>"
)
def __repr__(self):
return f"{self.label}: {self.value} ({self.change_pct}%)"
badge = MetricBadge("Monthly Revenue", "$45,200", 12.4)
display(badge)
If your code runs both in notebooks and in standard terminal scripts (such as CLI tools or cron tasks), calling display() in a pure Python terminal will raise a NameError unless imported. Write a safe helper function that falls back to print() when outside interactive notebooks:
def safe_display(obj):
try:
from IPython.display import display
from IPython import get_ipython
if get_ipython() is not None:
display(obj)
return
except (ImportError, NameError):
pass
# Fallback for standard command-line Python
print(obj)
Let's construct a verified component that builds an analytics summary card using custom HTML generation, and test its output structure with assertions:
class KPIDashboard:
def __init__(self, title):
self.title = title
self.metrics = {}
def add_metric(self, name, val):
self.metrics[name] = val
def _repr_html_(self):
rows = "".join(
f"<li><strong>{k}:</strong> {v}</li>" for k, v in self.metrics.items()
)
return f"<div class='kpi-panel'><h4>{self.title}</h4><ul>{rows}</ul></div>"
def __repr__(self):
return f"{self.title}: {self.metrics}"
# Build test dashboard
dash = KPIDashboard("Q3 System Health")
dash.add_metric("CPU Utilization", "28%")
dash.add_metric("Active Sessions", 1420)
dash.add_metric("Uptime", "99.98%")
# Unit Assertions
html_output = dash._repr_html_()
assert "<div class='kpi-panel'>" in html_output
assert "<h4>Q3 System Health</h4>" in html_output
assert "CPU Utilization:</strong> 28%" in html_output
assert repr(dash) == "Q3 System Health: {'CPU Utilization': '28%', 'Active Sessions': 1420, 'Uptime': '99.98%'}"
print("Generated HTML:", html_output)
print("All KPI dashboard unit assertions passed successfully!")
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.