[python] collapse cell in jupyter notebook

I am using ipython Jupyter notebook. Let's say I defined a function that occupies a lot of space on my screen. Is there a way to collapse the cell?

I want the function to remain executed and callable, yet I want to hide / collapse the cell in order to better visualize the notebook. How can I do this?

This question is related to python ipython ipython-notebook jupyter

The answer is


There's also an improved version of Pan Yan suggestion. It adds the button that shows code cells back:

%%html
<style id=hide>div.input{display:none;}</style>
<button type="button" 
onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">
Show inputs</button>

Or python:

# Run me to hide code cells

from IPython.core.display import display, HTML
display(HTML(r"""<style id=hide>div.input{display:none;}</style><button type="button"onclick="var myStyle = document.getElementById('hide').sheet;myStyle.insertRule('div.input{display:inherit !important;}', 0);">Show inputs</button>"""))

You don't need to do much except to enable the extensions:

http://localhost:8888/nbextensions?nbextension=collapsible_headings
http://localhost:8888/nbextensions?nbextension=codefolding/main

enter image description here

Most probable you will find all your extensions in here:

http://localhost:8888/nbextensions

enter image description here


As others have mentioned, you can do this via nbextensions. I wanted to give the brief explanation of what I did, which was quick and easy:

To enable collabsible headings: In your terminal, enable/install Jupyter Notebook Extensions by first entering:

pip install jupyter_contrib_nbextensions

Then, enter:

jupyter contrib nbextension install

Re-open Jupyter Notebook. Go to "Edit" tab, and select "nbextensions config". Un-check box directly under title "Configurable nbextensions", then select "collapsible headings".


I had a similar issue and the "nbextensions" pointed out by @Energya worked very well and effortlessly. The install instructions are straight forward (I tried with anaconda on Windows) for the notebook extensions and for their configurator.

That said, I would like to add that the following extensions should be of interest.

  • Hide Input | This extension allows hiding of an individual codecell in a notebook. This can be achieved by clicking on the toolbar button: Hide Input

  • Collapsible Headings | Allows notebook to have collapsible sections, separated by headings Collapsible Headings

  • Codefolding | This has been mentioned but I add it for completeness Codefolding


The hide_code extension allows you to hide individual cells, and/or the prompts next to them. Install as

pip3 install hide_code

Visit https://github.com/kirbs-/hide_code/ for more info about this extension.


Firstly, follow Energya's instruction:

pip install jupyter_contrib_nbextensions
jupyter contrib nbextension install --user
pip install jupyter_nbextensions_configurator
jupyter nbextensions_configurator enable --user

Second is the key: After opening jupiter notebook, click the Nbextension tab. Now Search "colla" from the searching tool provided by Nbextension(not by the web browser), then you will find something called "Collapsible Headings"

This is what you want!


You can create a cell and put the following code in it:

%%html
<style>
div.input {
    display:none;
}
</style>

Running this cell will hide all input cells. To show them back, you can use the menu to clear all outputs.

Otherwise you can try notebook extensions like below:

https://github.com/ipython-contrib/IPython-notebook-extensions/wiki/Home_3x


What I use to get the desired outcome is:

  1. Save the below code block in a file named toggle_cell.py in the same directory as of your notebook
from IPython.core.display import display, HTML
toggle_code_str = '''
<form action="javascript:code_toggle()"><input type="submit" id="toggleButton" value="Show Sloution"></form>
'''

toggle_code_prepare_str = '''
    <script>
    function code_toggle() {
        if ($('div.cell.code_cell.rendered.selected div.input').css('display')!='none'){
            $('div.cell.code_cell.rendered.selected div.input').hide();
        } else {
            $('div.cell.code_cell.rendered.selected div.input').show();
        }
    }
    </script>

'''

display(HTML(toggle_code_prepare_str + toggle_code_str))

def hide_sloution():
    display(HTML(toggle_code_str))
  1. Add the following in the first cell of your notebook
from toggle_cell import toggle_code as hide_sloution
  1. Any cell you need to add the toggle button to simply call hide_sloution()

Create custom.js file inside ~/.jupyter/custom/ with following contents:

$("<style type='text/css'> .cell.code_cell.collapse { max-height:30px; overflow:hidden;} </style>").appendTo("head");
$('.prompt.input_prompt').on('click', function(event) {
    console.log("CLICKED", arguments)   
    var c = $(event.target.closest('.cell.code_cell'))
    if(c.hasClass('collapse')) {
        c.removeClass('collapse');
    } else {
        c.addClass('collapse');
    }
});

After saving, restart the server and refresh the notebook. You can collapse any cell by clicking on the input label (In[]).


JupyterLab supports cell collapsing. Clicking on the blue cell bar on the left will fold the cell. enter image description here


There are many answers to this question, all of which I feel are not satisfactory (some more than others), of the many extensions - code folding, folding by headings etc etc. None do what I want in simple and effective way. I am literally amazed that a solution has not been implemented (as it has for Jupyter Lab).

In fact, I was so dissatisfied that I have developed a very simple notebook extension that can expand/collapse the code in a notebook cell, while keeping it executable.

The GitHub repository: https://github.com/BenedictWilkinsAI/cellfolding

Below is a small demo of what the extension does:

Simply double clicking left of the code cell will collapse it to a single line:

Double clicking again will expand the cell.

The extension can be installed easily with pip:

pip install nbextension-cellfolding
jupyter nbextension install --py cellfolding --user
jupyter nbextension enable --py cellfolding --user 

and is also compatible with nbextension configurator. I hope that people will find this useful!


Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to ipython

How to increase image size of pandas.DataFrame.plot in jupyter notebook? Importing .py files in Google Colab Selection with .loc in python IOPub data rate exceeded in Jupyter notebook (when viewing image) Purpose of "%matplotlib inline" Installing a pip package from within a Jupyter Notebook not working convert json ipython notebook(.ipynb) to .py file In which conda environment is Jupyter executing? How to make inline plots in Jupyter Notebook larger? %matplotlib line magic causes SyntaxError in Python script

Examples related to ipython-notebook

collapse cell in jupyter notebook Simple way to measure cell execution time in ipython notebook Using both Python 2.x and Python 3.x in IPython Notebook How do I add python3 kernel to jupyter (IPython) How to hide code from cells in ipython notebook visualized with nbviewer? Show DataFrame as table in iPython Notebook How to show PIL Image in ipython notebook ipython notebook clear cell output in code Format certain floating dataframe columns into percentage in pandas Pandas - Plotting a stacked Bar Chart

Examples related to jupyter

How to increase image size of pandas.DataFrame.plot in jupyter notebook? What is the difference between Jupyter Notebook and JupyterLab? Removing Conda environment How to open local file on Jupyter? Jupyter notebook not running code. Stuck on In [*] Can I run Keras model on gpu? IOPub data rate exceeded in Jupyter notebook (when viewing image) How to execute a * .PY file from a * .IPYNB file on the Jupyter notebook? how to make a new line in a jupyter markdown cell Running Jupyter via command line on Windows