In a Jupyter Notebook, each code cell does not have a built-in "index" or "random identifier" attribute that you can directly access from within the cell itself. However, there are a few workarounds depending on what you need:
In Prompt NumberEach executed cell in Jupyter has an In [X] prompt, where X is the execution count. You can access this number using the In list from the IPython shell:
pythonfrom IPython.display import display from IPython import get_ipython # Get the current execution count execution_count = get_ipython().execution_count print(f"Current execution count: {execution_count}")
Note: This only works for the most recently executed cell and is not a unique identifier.
If you want a more persistent identifier, you can use the notebook's JSON structure. Each cell has a unique id in the notebook's metadata. You can access this via the nbformat library:
pythonimport nbformat from IPython.display import display, Javascript # Get the current notebook's JSON notebook = get_ipython().notebook.notebook # Find the current cell's index current_cell_index = get_ipython().execution_count - 1 # Get the cell's ID (if available) cell_id = notebook.cells[current_cell_index].get('id', 'No ID found') print(f"Current cell ID: {cell_id}")
Note: This requires the notebook to be saved and the cell IDs to be present (JupyterLab/Jupyter Notebook 5.0+).
If you want to interact with the notebook's frontend (e.g., to get the cell index or ID dynamically), you can use JavaScript:
pythonfrom IPython.display import display, Javascript js = """ var cell = Jupyter.notebook.get_selected_cell(); var cell_index = Jupyter.notebook.find_cell_index(cell); var cell_id = cell.element[0].id; console.log("Cell index:", cell_index); console.log("Cell ID:", cell_id); """ display(Javascript(js))
Note: This will print the index and ID to the browser's console.
%%javascript MagicYou can also use the %%javascript cell magic to run JavaScript directly in a cell:
python%%javascript var cell = Jupyter.notebook.get_selected_cell(); var cell_index = Jupyter.notebook.find_cell_index(cell); var cell_id = cell.element[0].id; console.log("Cell index:", cell_index); console.log("Cell ID:", cell_id);
execution_countnbformat%%javascript Magic