Working with Colab Notebooks Intermediate
Colab notebooks are powerful interactive documents that combine executable code, rich text, visualizations, and more. This lesson covers cells, magic commands, package management, Google Drive integration, and collaboration features.
Code Cells and Text Cells
Colab notebooks contain two types of cells:
- Code cells: Execute Python code. Output appears directly below the cell. Variables persist across cells within the same runtime session.
- Text cells: Use Markdown for documentation. Support headings, lists, links, images, LaTeX math, and HTML.
# Code cell example: variables persist across cells
data = [1, 2, 3, 4, 5]
total = sum(data)
print(f"Sum: {total}, Mean: {total/len(data)}")
Magic Commands
Colab supports IPython magic commands that extend beyond standard Python:
# Line magics (single %)
%timeit sum(range(1000)) # Time a single line
%who # List all variables
%whos # List variables with details
%env MY_VAR=value # Set environment variable
%matplotlib inline # Enable inline plots
# Cell magics (double %%)
%%timeit # Time the entire cell
x = sum(range(1000))
%%capture output # Capture cell output
print("This is captured")
%%writefile script.py # Write cell contents to file
print("Hello from script")
%%bash # Run bash commands
echo "Hello from bash"
ls -la
Installing Packages
Use the ! prefix to run shell commands, including pip:
# Install a package
!pip install transformers
# Install a specific version
!pip install pandas==2.1.0
# Install multiple packages
!pip install plotly bokeh streamlit
# Install from a requirements file
!pip install -r requirements.txt
# Upgrade a package
!pip install --upgrade scikit-learn
# Check installed version
!pip show tensorflow
Important: Installed packages persist only for the current session. When the runtime disconnects or resets, you need to reinstall them. Place your
!pip install commands at the top of your notebook for easy re-execution.Importing Libraries
Many popular libraries are pre-installed in Colab:
# Pre-installed in Colab
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
import sklearn
import tensorflow as tf
import torch
# Check versions
print(f"NumPy: {np.__version__}")
print(f"Pandas: {pd.__version__}")
print(f"TensorFlow: {tf.__version__}")
print(f"PyTorch: {torch.__version__}")
Forms and Interactive Widgets
Colab supports special form fields and interactive widgets:
# @title Form Fields Example
name = "World" # @param {type:"string"}
count = 3 # @param {type:"integer"}
rate = 0.5 # @param {type:"number"}
use_gpu = True # @param {type:"boolean"}
for i in range(count):
print(f"Hello, {name}! (iteration {i+1})")
# Interactive widgets with ipywidgets
from ipywidgets import interact, widgets
@interact(x=(0, 10, 1), y=(0, 10, 1))
def multiply(x=3, y=5):
print(f"{x} * {y} = {x * y}")
Mounting Google Drive
Access your Google Drive files directly from Colab:
from google.colab import drive
drive.mount('/content/drive')
# Now access files at /content/drive/MyDrive/
import pandas as pd
df = pd.read_csv('/content/drive/MyDrive/data/my_dataset.csv')
print(df.head())
Tip: When you run
drive.mount(), Colab will prompt you to authorize access. Click the link, sign in with your Google account, and paste the authorization code back into the notebook.Sharing Notebooks
Share Colab notebooks just like Google Docs:
- Share button: Click "Share" in the top-right corner to share with specific people or create a link
- Permissions: Set viewers (can run but not edit), commenters, or editors
- Copy link: Anyone with the link can view or copy the notebook
- Publish: Share on social media or embed in websites
Version History
Colab keeps track of changes to your notebooks:
- Go to File → Revision history to see all past versions
- Name important versions with File → Save and pin revision
- Restore any previous version by selecting it from the history
- Compare changes between versions side by side
Collaboration Features
Colab supports real-time collaboration similar to Google Docs:
- Real-time editing: Multiple users can edit the same notebook simultaneously
- Cursor visibility: See where collaborators are editing in real time
- Chat: Use the built-in chat panel to communicate while working together
- Comments: Add comments to specific cells for code review or discussion
- Shared runtime: Each collaborator gets their own runtime, so running code does not interfere
Lilly Tech Systems