ENGIMY.IO - CHEATSHEET
GOOGLE COLAB × CLOUD NOTEBOOKS
REFERENCE vGoogle Colab (current)

Google Colab Quick Reference

Run Jupyter notebooks in the cloud with free GPUs, TPUs, and seamless sharing.

Getting Started

  • Access: https://colab.research.google.com
  • Sign in: Google account required.
  • Create new: File → New Notebook.
  • Open from GitHub: File → Open → GitHub (paste repo URL).
  • Upload: File → Upload notebook (from local or Drive).

Keyboard Shortcuts

Most Jupyter shortcuts work, plus a few Colab-specific ones.

Shortcut Action
Ctrl+EnterRun cell
Shift+EnterRun cell and select below
Ctrl+M BInsert cell below
Ctrl+M AInsert cell above
Ctrl+M DDelete selected cell
Ctrl+M ZUndo cell deletion
Ctrl+M YChange to Code cell
Ctrl+M MChange to Markdown cell
Ctrl+M RChange to Raw cell
Ctrl+M HShow shortcuts
Ctrl+SSave (automatic, but manual available)
Ctrl+Shift+PCommand palette
Ctrl+Shift+CCopy cell

Hardware Acceleration

Enable GPU or TPU for faster training.

# Menu: Runtime → Change runtime type
Hardware accelerator: None / GPU / TPU

# Check if GPU is available
import tensorflow as tf
tf.config.list_physical_devices('GPU')

# Check TPU
import os
if 'COLAB_TPU_ADDR' in os.environ:
    print('TPU available')

# CPU info
!cat /proc/cpuinfo | grep "model name" | head -1

# GPU info (NVIDIA)
!nvidia-smi

# RAM
!free -h

File System and Data Access

Colab provides a temporary VM with a Linux filesystem.

Mount Google Drive
# Mount Drive for persistent storage
from google.colab import drive
drive.mount('/content/drive')

# Now you can read/write to /content/drive/MyDrive/
!ls /content/drive/MyDrive/

# Example: Load CSV from Drive
import pandas as pd
df = pd.read_csv('/content/drive/MyDrive/data.csv')
Upload/Download Files
# Upload via UI: Files → Upload

# Or programmatically
from google.colab import files
uploaded = files.upload()   # opens file chooser

# Download files
files.download('output.csv')
Access External Data
# From URL (wget/curl)
!wget https://example.com/data.zip
!unzip data.zip

# From GitHub raw
!wget https://raw.githubusercontent.com/user/repo/main/data.csv

Magic Commands

Same as IPython/Jupyter with some Colab-specific additions.

System Commands (!)
!ls -la
!pip install numpy
!git clone https://github.com/user/repo
!python script.py

# Capture output
output = !ls -la
print(output)
Line Magics (%)
%time
%timeit
%run script.py
%matplotlib inline
%cd /content/drive/MyDrive/
Cell Magics (%%)
%%bash
echo "Hello from bash"
ls

%%html

HTML output

%%writefile myfile.txt content to write

Environment Variables

# Set environment variables
import os
os.environ['MY_VAR'] = 'value'

# Or use %env
%env MY_VAR=value

# Access
print(os.environ['MY_VAR'])

# Preserve between sessions? Use Drive mount or secrets

Secret Management

Store secrets (API keys, passwords) in Colab Secrets.

# Access via userdata
from google.colab import userdata
api_key = userdata.get('API_KEY')

# Set in UI: Keys (left sidebar) → Add key
# Not visible in notebook, secure.

Collaboration

  • Share: Click "Share" button (top right) → set permissions.
  • View-only / Edit / Comment modes.
  • Live collaboration – multiple people can edit simultaneously (like Google Docs).
  • Comments – add comments on specific cells.
  • Version history – File → Revision history.

Running Cells with Different Runtimes

  • Restart runtime – Runtime → Restart runtime (clears all variables).
  • Restart and run all – Runtime → Run all (restarts first).
  • Interrupt – Runtime → Interrupt execution (or click stop button).
  • Factory reset – Runtime → Factory reset runtime (for clean state).

Installing Packages

# Standard pip
!pip install pandas numpy matplotlib

# Install specific version
!pip install tensorflow==2.15.0

# From GitHub
!pip install git+https://github.com/user/repo.git

# Conda (if needed)
!conda install -c conda-forge opencv -y

# Apt-get (for system libraries)
!apt-get update && apt-get install -y ffmpeg

Visualisation

# Matplotlib (inline)
%matplotlib inline
import matplotlib.pyplot as plt
plt.plot([1, 2, 3, 4])
plt.show()

# Plotly (interactive)
import plotly.express as px
fig = px.scatter(...)
fig.show()  # renders in Colab

# Seaborn
import seaborn as sns
sns.heatmap(df.corr())

Handling Large Files and Data

Colab has limited disk (≈100GB) and RAM (≈12-25GB depending on runtime).

  • Use Drive – mount and read/write directly; avoid copying large datasets into VM.
  • Use cloud storage – load from S3, GCS, or BigQuery.
  • Streaming – use pandas.read_csv() with chunksize.
  • Delete unused files!rm -rf large_file.
  • Check disk usage!df -h /content.
  • Garbage collectimport gc; gc.collect().

Colab Pro / Pro+ Features

  • Better GPUs – A100, V100, T4 (depending on plan).
  • More RAM – higher memory instances.
  • Longer runtimes – up to 24 hours (vs 12 for free).
  • Background execution – notebook keeps running even if browser closed (Pro+).

Export / Download

  • Save to Drive – File → Save a copy in Drive.
  • Download – File → Download .ipynb, .py, .html, etc.
  • GitHub – File → Save a copy to GitHub (requires auth).

Common Code Snippets

Mount Drive and change working directory
from google.colab import drive
drive.mount('/content/drive')
import os
os.chdir('/content/drive/MyDrive/Colab Notebooks')
!pwd
Clone a GitHub repo
!git clone https://github.com/user/repo.git
%cd repo
Unzip a file
!unzip -q archive.zip -d extracted/
List files in Drive
!ls -l /content/drive/MyDrive/
Read CSV from Drive
import pandas as pd
df = pd.read_csv('/content/drive/MyDrive/data.csv')
Save DataFrame to CSV in Drive
df.to_csv('/content/drive/MyDrive/output.csv', index=False)

Best Practices

  • Mount Drive at start – for persistent data access.
  • Use environment variables – for configurable paths.
  • Install dependencies upfront – in the first cell.
  • Use %%capture to suppress excessive output.
  • Clear output – to reduce notebook size (Edit → Clear all outputs).
  • Save to GitHub – version control your notebooks.
  • Use userdata – for secrets instead of hard-coding.
  • Monitor runtime – use !nvidia-smi for GPU usage.
  • Set %matplotlib inline – for plots.
  • Restart runtime – before sharing to ensure reproducibility.
  • Use !pip install with --quiet to reduce log noise.

Troubleshooting

  • GPU not detected? – ensure runtime type is GPU; check !nvidia-smi.
  • Out of memory? – reduce batch size, use garbage collection, mount Drive.
  • Drive not mounted? – re‑run drive.mount() and allow access.
  • Package version conflicts? – use !pip install package==version.
  • Timeout? – keep notebook active; reconnect if idle.
  • Not saving? – Colab auto‑saves, but also use File → Save.
📌 Quick Reference
Mount Drive: drive.mount('/content/drive')
GPU: Runtime → Change runtime type → GPU
Key magics: %time, %matplotlib inline, !ls, %%bash
Secrets: from google.colab import userdata; userdata.get('KEY')
Upload/Download: files.upload() / files.download()
Shortcut: Ctrl+M H for help
Best practice: Save to GitHub, use Drive for data, restart before sharing
← Back to All Cheatsheets