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!