Excellent, Assistant Lecturer — below is a complete, carefully-structured tutorial pack for
learning Biopython 1.85 with Python 3.11. It is written for a beginner in biology but an
experienced programmer/data scientist: every code snippet is accompanied by line-by-line
explanations in plain language, and the sequence of topics is organised so you can learn,
practice, and become contribution-ready.
I will cover:
1. quick checks & installation (conda/pip) — which to use and how;
2. verifying your environment and Biopython version;
3. Seq and SeqRecord (core sequence objects) with line-by-line examples;
4. reading & writing files with SeqIO (FASTA, FASTQ, GenBank) with examples;
5. common sequence operations (reverse complement, translate, GC%);
6. pairwise & multiple alignments (pairwise2 and [Link]) with examples;
7. fetching sequences programmatically with Entrez (NCBI) and parsing BLAST output;
8. a practical ML example: convert DNA sequences to k-mer features and train a simple
classifier (pandas + scikit-learn);
9. practical tips: using help() & docstrings, testing, notebooks vs VS Code, and next steps
toward contribution.
Where useful I cite the official Biopython docs and install recommendations so you know the
authoritative source. Biopython+4Biopython+4Biopython+4
1 — Installation & quick verification (conda /
pip)
Recommendation: For learning and development on your machine, prefer conda (conda-forge)
because it handles binary dependencies reliably. Use pip if you prefer virtualenv or when
contributing (you’ll often pip install -e . when working from the source). Official
guidance: pip install biopython is supported; conda-forge packages are also maintained.
Biopython+1
Conda (recommended):
conda create -n biopython-dev python=3.11 -y
conda activate biopython-dev
conda install -c conda-forge biopython jupyterlab ipykernel -y
Creates and activates a clean environment (biopython-dev) with Python 3.11.
Installs Biopython from conda-forge (stable binary builds), JupyterLab, and the kernel.
Pip (alternative):
python -m venv venv
source venv/bin/activate # or venv\Scripts\activate on Windows
pip install --upgrade pip
pip install biopython jupyterlab
Verify Biopython version (run in the environment you will use):
import Bio
print("Biopython:", Bio.__version__)
This confirms you have Biopython 1.85 (or the installed version) active in the
environment.
Docs and tutorial reference (useful while learning): Biopython Tutorial & Cookbook (v1.85).
Biopython
2 — Core objects: Seq and SeqRecord
Biopython represents biological sequences with Seq (just the sequence) and SeqRecord
(sequence + annotation/metadata). Use Seq for sequence operations and SeqRecord for
reading/writing and storing IDs/annotations.
Example 2.1 — Basic Seq usage
from [Link] import Seq
dna = Seq("ATGCGTACGTAGCTAGCTAG") # 1
print("Length:", len(dna)) # 2
print("Slice [0:6]:", dna[0:6]) # 3
print("Reverse complement:", dna.reverse_complement()) # 4
print("Translate:", [Link]()) # 5
Line-by-line explanation
1. Seq("..."): create a Seq object holding the DNA letters (A,T,G,C). This object has
sequence methods attached.
2. len(dna): returns the number of bases (nucleotides).
3. dna[0:6]: Python slicing works — returns the first six bases (like list/string slicing).
4. dna.reverse_complement(): computes the reverse complement (A↔T, C↔G and
reversed). This models the opposite DNA strand.
5. [Link](): converts the coding DNA sequence into an amino-acid string using
the standard genetic code (three bases → one amino acid). If the sequence length is not a
multiple of three, Biopython handles stop codons with * or you can specify behavior.
Example 2.2 — SeqRecord with metadata
from [Link] import Seq
from [Link] import SeqRecord
record = SeqRecord(Seq("ATGCGTACGTAG"), id="seq1", name="Example",
description="Synthetic example")
print([Link]) # "seq1"
print([Link]) # "Synthetic example"
print([Link]) # Seq object accessible via .seq
SeqRecord bundles Seq with id, name, description and an optional annotations dict
and features list for richer information.
3 — Reading and writing sequences: SeqIO
(FASTA, FASTQ, GenBank)
SeqIO is Biopython’s unified I/O interface: [Link]() for reading many records,
[Link]() for exactly one record, and [Link]() to write records.
Example 3.1 — Read FASTA from a string (Jupyter friendly)
from Bio import SeqIO
from io import StringIO
fasta = """>seq1 description
ATGCGTACGTAGCTAGCTAG
>seq2
ATGCGTACGATAG
"""
handle = StringIO(fasta) # 1
for rec in [Link](handle, "fasta"): # 2
print([Link], len([Link])) # 3
Explanation
1. StringIO lets us treat the multi-line string as a file handle (handy for demos without disk
files).
2. [Link](handle, "fasta") returns an iterator of SeqRecord objects parsed from
FASTA.
3. [Link] is the sequence identifier (first word after >), len([Link]) its length.
Example 3.2 — Write SeqRecord(s) to FASTA
from Bio import SeqIO
from [Link] import Seq
from [Link] import SeqRecord
from io import StringIO
records = [
SeqRecord(Seq("ATGCGTACGTAGCTAGCTAG"), id="seq1", description="example
one"),
SeqRecord(Seq("ATGCGTACGATAG"), id="seq2", description="example two"),
]
output = StringIO()
[Link](records, output, "fasta") # writes all records to the StringIO
handle
print([Link]()) # display FASTA text
GenBank example (reading)
# If you have a GenBank file '[Link]':
for rec in [Link]("[Link]", "genbank"):
print([Link], [Link]("source"), len([Link]))
# [Link] contains SeqFeature objects (genes, CDS, etc.)
GenBank parsing yields rich features and annotations. See [Link] for
handling genomic annotations. Biopython
4 — Common sequence utilities (GC%,
translating, counting)
Biopython includes SeqUtils for helpful functions.
Example 4.1 — GC content & simple counts
from [Link] import GC
from [Link] import Seq
s = Seq("ATGCGTACGTAGCTAGCTAG")
print("GC%:", GC(s)) # GC percentage
print("A count:", [Link]("A")) # count of A bases
GC() computes percentage of G+C bases (important to characterise sequences).
Note: [Link]() counts occurrences like a Python string method.
5 — Alignments: pairwise2 and [Link]
Biopython offers older pairwise2 and newer [Link] / Align objects. For learning, show
both.
Example 5.1 — Pairwise alignment with pairwise2
from Bio import pairwise2
from Bio.pairwise2 import format_alignment
s1 = "ACCGT"
s2 = "ACG"
alns = [Link](s1, s2) # 1: global alignment, score by
matches
print("Number of alignments:", len(alns))
for a in alns:
print(format_alignment(*a)) # 2: nicely formatted string
Explanation
1. globalxx does a global alignment with a simple scoring: +1 for match, 0 otherwise. It
returns a list of alignment tuples.
2. format_alignment prints alignment with matching columns and score.
Example 5.2 — Using [Link] (object oriented)
from Bio import Align
aligner = [Link]()
[Link] = "global"
alignments = [Link]("ACCGT", "ACG")
print("Best score:", [Link])
for a in alignments:
print(a) # object representation; supports .format() or str()
[Link] modern API and alignment objects with methods and attributes
(recommended for new code).
(See Biopython alignment docs for in-depth details.) Biopython
6 — BLAST: running & parsing
You can either run BLAST locally (requires NCBI BLAST+ binaries) or call NCBI’s remote
BLAST (slower and usewise limited). Biopython has [Link] for remote
queries and [Link] to parse XML output. (Use responsibly, follow NCBI usage
policies.) Biopython
Example 6.1 — Parse a local BLAST XML (parsing demo)
from [Link] import NCBIXML
# Suppose you have 'blast_output.xml' from a BLAST run on disk:
with open("blast_output.xml") as handle:
blast_records = [Link](handle) # iterator over Blast records
for br in blast_records:
print("Query:", [Link])
for alignment in [Link]:
for hsp in [Link]:
print("Hit:", alignment.hit_id, "score:", [Link], "e-
value:", [Link])
Notes
[Link] parses BLAST XML into objects like [Link], which contain
alignments and hsps (high-scoring pairs).
For live queries: [Link]("blastn", "nt", "ACTG...") returns
an HTTP handle — avoid heavy use.
7 — Fetching sequences with Entrez (NCBI)
You must provide an email (required) and ideally an API key for higher rate limits. Use
[Link] to search & fetch.
Example 7.1 — Fetch a GenBank record by accession
from Bio import Entrez, SeqIO
[Link] = "[Link]@[Link]" # 1
Entrez.api_key = "YOUR_NCBI_API_KEY" # optional, 2
handle = [Link](db="nucleotide", id="NM_000546", rettype="gb",
retmode="text") # 3
record = [Link](handle, "genbank") # 4
[Link]()
print([Link], [Link])
print("First 60 bases:", [Link][:60])
Line-by-line
1. Set a contact email so NCBI can contact you if needed.
2. Optional API key for higher request quotas.
3. efetch gets the record from NCBI nucleotide DB; specify return type.
4. [Link] parses a single GenBank record into a SeqRecord.
Caution: respect NCBI policies, add delays between queries, and use bulk download tools for
large datasets.
8 — Practical ML example: k-mer features
→ classifier
As a data scientist, you will often convert sequences into numeric features. A common approach
is k-mer counts (substrings of length k). Here is a compact example turning DNA sequences
into 3-mer counts and training a classifier.
Example 8.1 — k-mer vectorization + scikit-learn
# Requires: pip install scikit-learn pandas
from sklearn.feature_extraction.text import CountVectorizer
from [Link] import RandomForestClassifier
from sklearn.model_selection import train_test_split
from [Link] import Seq
import pandas as pd
# Example sequences (toy data)
seqs = ["ATGCGTACGTAG", "ATGCGTACGATG", "GCTAGCTAGCTA", "GCTAGCTGGGTT"]
labels = [0,0,1,1] # pretend two classes
# 1. Convert to "k-mer strings", using k=3
def kmers(seq, k=3):
return " ".join([seq[i:i+k] for i in range(len(seq)-k+1)])
k = 3
docs = [kmers(s, k) for s in seqs] # e.g. "ATG TGC GCG ..."
# 2. Use CountVectorizer on the space-separated k-mers
vec = CountVectorizer(token_pattern=r"(?u)\b\w+\b") # tokens are the kmer
words
X = vec.fit_transform(docs)
df = [Link]([Link](), columns=vec.get_feature_names_out())
# 3. Train/test split and a simple classifier
X_train, X_test, y_train, y_test = train_test_split(df, labels, test_size=0.5,
random_state=42)
clf = RandomForestClassifier(n_estimators=50, random_state=42)
[Link](X_train, y_train)
print("Test accuracy:", [Link](X_test, y_test))
Explanation
kmers slides a window of length k producing overlapping k-mer tokens; we separate
tokens with spaces so CountVectorizer can ingest them like words.
CountVectorizer builds a vocabulary of observed k-mers and returns a sparse matrix of
counts.
We train a RandomForestClassifier on the resulting feature vectors.
Why this works for DNA: k-mers capture local sequence patterning; for larger real datasets you
may use TF, TF-IDF, or embedding approaches (CNNs/RNNs/transformers).
9 — Practical learning tips, help(), and
docstrings
When uncertain: help([Link]) or from Bio import SeqIO; help(SeqIO) —
Biopython modules include docstrings and examples.
The tutorial chapters are excellent for incremental learning; consult the SeqIO and Seq
object chapters for more examples. Biopython+1
For interactive exploration, use Jupyter notebooks and test each method on small toy
sequences first.
10 — Exercises (progressive) — do these in
Jupyter
Beginner
1. Parse a local FASTA file of 10 sequences; compute length & GC% for each and plot a
histogram of lengths (matplotlib).
2. Create SeqRecords with annotations and write them to a GenBank file.
Intermediate
3. Write a function to detect open reading frames (ORFs) in a DNA Seq.
4. Read a small BLAST XML file and extract top hit IDs.
Advanced
5. Build an RNA-seq like toy pipeline: simulate sequences labeled by a class, extract k-mer
features, and train several classifiers; compare performance.
6. Write a small SeqIO plugin (or test) that handles a simple edge case for an uncommon FASTA
header — submit as a PR.
11 — Notes about notebooks vs VS Code &
progressing to contributions
Jupyter: best for learning, experiments, tutorials, and creating shareable notebooks for
your GitHub portfolio.
VS Code: best for editing project code, running tests, creating PRs, and debugging. Set
VS Code to use the biopython-dev interpreter and enable pytest integration.
Practice path I recommend: spend 2–4 weeks with the examples above, build 2–3
notebook tutorials that you can publish to GitHub (e.g.,
notebooks/SeqIO_quickstart.ipynb, notebooks/kmer_classification.ipynb).
These serve both learning and portfolio evidence.
When ready to contribute to Biopython source: fork the repo, clone, pip install -e
. inside the cloned repo, run tests, and pick small issues (docs/typos/unit tests) first.
12 — Short checklist to run an example
notebook now
1. Activate your conda env: conda activate biopython-dev
2. Launch JupyterLab: jupyter lab
3. Create a new notebook with kernel Python (biopython-dev)
4. Copy the Seq / SeqRecord examples and run them line by line.
5. Save and publish to your GitHub as notebooks/[Link].
13 — Where to read next (official resources)
Biopython Tutorial & Cookbook (v1.85) — the canonical step-by-step tutorial.
Biopython
SeqIO API chapter (formats & examples). Biopython
Biopython BLAST chapter for parsing BLAST outputs. Biopython
Installation & conda-forge info for binary installs. Anaconda+1
14 — Next steps (contribution readiness)
1. Convert one of your Jupyter notebooks into a well-documented tutorial (README +
notebook).
2. Fork Biopython repo; search issues with labels documentation, good first issue,
help wanted.
3. Start with a documentation fix: small PRs are reviewed faster. Use git workflow
described earlier.
4. When ready, pick a small code issue (unit test or small bug) and open a development
branch.