Skip to content
Tutorials Center
My learning

Topics

Lesson 4 of 49 ยท Getting Started

Working with sequences in Python

Build a small Python toolkit for DNA: indexing and slicing, base counts, GC content, sliding windows, k-mers and a hand-written FASTA parser.

Python strings are almost a perfect fit for biological sequences. They are ordered, you can slice them, you can count letters in them and a single string holds a whole chromosome. In this lesson you will build, from scratch, the handful of functions that most sequence scripts reuse: counting bases, computing GC content, sliding windows, k-mers and a parser for the FASTA format. Real projects usually use the Biopython library for these tasks, but writing them once yourself is the fastest way to understand what the library does.

The sequence ATGCGTAC with six coloured three-letter windows, each shifted one base, and the six k-mers listed
Caption: a sequence of length L contains L - k + 1 overlapping k-mers.

What you will learn

  • How indexing and slicing work on sequences, including Python's 0-based, end-exclusive rule.
  • How to count bases and compute GC content, and why GC content is informative.
  • How sliding windows and k-mers turn a long sequence into many small, comparable pieces.
  • How to parse a multi-record FASTA text into a dictionary.

Key terms

  • GC content: the fraction of bases that are G or C. Human DNA averages about 41%; bacterial genomes range from roughly 25% to 75%.
  • k-mer: a substring of length k. A 3-mer is also called a trimer or, in a coding frame, a codon.
  • Sliding window: a fixed-length stretch that moves along a sequence one step at a time, with a summary calculated at each position.
  • FASTA: a text format where a line starting with > names a record and the following lines hold its sequence.

Indexing and slicing

A Python string indexes from 0. For seq = "ATGCGTAC", seq[0] is A and seq[7] is C. Negative indexes count from the end, so seq[-1] is the last letter. A slice seq[a:b] returns positions a up to but not including b, which is why seq[2:5] is GCG (positions 2, 3 and 4). The end-exclusive rule feels odd at first, but it has two benefits: the length of a slice is simply b - a, and adjacent slices seq[0:3] and seq[3:6] fit together without overlap or gap. That is exactly what you want when you chop a coding sequence into codons.

Biologists, however, count from 1, and databases often give feature positions as 1-based and inclusive. A gene "from 101 to 220" in a GenBank record means Python's seq[100:220]. Mixing up the two systems is one of the most common off-by-one errors in the field, and chapter 2 returns to it when it covers file formats.

Counting bases and GC content

The count method counts non-overlapping occurrences of a substring, so seq.count("G") counts guanines. For all four bases at once, use a dictionary or collections.Counter. GC content is then (G + C) / length.

GC content is one of the first numbers computed for any new genome, because it carries biological signal. G-C pairs have three hydrogen bonds and A-T pairs have two, so GC-rich DNA melts at a higher temperature, which matters for designing PCR primers. GC content also varies along genomes: in mammals, stretches called CpG islands are GC-rich and often mark the start of genes. Unusual GC content in a stretch of bacterial genome can hint that the segment was acquired from another species by horizontal gene transfer. Sequencing itself is also GC-sensitive, since extreme GC regions tend to be covered less evenly.

Sliding windows

One global number hides local structure. To see variation along a sequence, compute GC content in a window of fixed size (say 40 bases) that steps along the sequence (say 10 bases at a time). The result is a profile that you can plot. In the code below you will build a synthetic sequence with a GC-rich island and watch it emerge.

The window and step are choices, and they matter. A small window is noisy, because a handful of letters gives a wildly varying fraction. A large window smooths the noise but blurs boundaries. Reading the profile is a skill you will use again with sequencing coverage and conservation scores.

k-mers: turning sequences into words

A k-mer is any substring of length k. Sliding a window of size k with step 1 produces every k-mer, and a sequence of length L has L - k + 1 of them. For ATGCGTAC and k = 3 there are 6: ATG, TGC, GCG, CGT, GTA, TAC. Counting how often each k-mer occurs gives a compact fingerprint of a sequence, and k-mers are the foundation of many tools: BLAST uses short words to find matches, genome assemblers link overlapping k-mers into graphs, and some classifiers detect species from k-mer frequencies alone.

The number of possible k-mers is 4^k (4 for k = 1, 16 for k = 2, 64 for k = 3, and over a million at k = 10). That exponential growth limits how large k can be in a dense table, and it explains why real tools hash k-mers. A k that is too small is uninformative because everything looks alike; one that is too large makes most k-mers unique and sensitive to a single sequencing error.

Parsing FASTA

A FASTA record has a header line beginning with >, normally an identifier followed by a free-text description, and then one or more lines of sequence. The parser logic is simple: when you meet a >, start a new record; otherwise append the line (stripped of whitespace) to the current record. Keeping records in a dictionary from identifier to sequence makes lookup easy. Always uppercase the sequence, because many files use lowercase for soft-masked repeats, and strip stray whitespace.

In production code, use Bio.SeqIO.parse(handle, "fasta") from Biopython. It handles odd line endings, huge files (it streams one record at a time rather than reading the whole file into memory) and dozens of other formats.

Putting it together

Combine the pieces into a tiny workflow. Parse a FASTA text into a dictionary, loop over its records, and for each one report the length, the GC content and the most frequent 3-mer. Then pick the record with the highest GC content and plot its window profile. Notice how little code this needs: each step is a function you already wrote, and the loop only wires them together. That is the habit to build. Write small functions that do one thing, test them on a tiny input where you know the answer, and only then apply them to a real file.

Also practice defensive habits from the start. Uppercase every sequence, strip whitespace, check that a record is not empty before dividing by its length (the parser example shows what happens with an empty record), and decide in advance what to do with ambiguous bases such as N, which stands for any base and should usually be excluded from GC calculations.

Common misconceptions

  • "seq[2:5] includes position 5." It does not. The end of a slice is exclusive.
  • "str.count finds overlapping matches." It does not: "AAAA".count("AA") is 2, not 3. To count overlapping k-mers, slide a window.
  • "GC content of a genome is the same everywhere." It varies between species and along a single genome.
  • "Lowercase letters are errors." In genome FASTA files, lowercase usually marks repeats that were masked, not mistakes.

Try it

Python A sequence toolkit

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A GC-rich island in a sliding window

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python A hand-written FASTA parser

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does seq[2:5] return for seq = 'ATGCGTAC'?

    Positions 2, 3 and 4 are G, C and G. The end index 5 is excluded.
  2. 2. How many 4-mers does a sequence of length 20 contain?

    L - k + 1 = 20 - 4 + 1 = 17 overlapping 4-mers.
  3. 3. What is the GC content of ATGCGCAT?

    G or C appears at four positions (G, C, G, C) out of 8, so the GC content is 50%.
  4. 4. A GenBank feature spans 101 to 220 (1-based, inclusive). Which Python slice extracts it?

    1-based position 101 is index 100, and an inclusive end of 220 is the exclusive end index 220.
  5. 5. Why does a large k make k-mer methods fragile for sequencing reads?

    A single wrong base changes all k-mers that include it, so larger k means more k-mers affected per error.

Summary

  • Python slices are 0-based and end-exclusive; biological coordinates are often 1-based and inclusive.
  • GC content, base counts and k-mer counts are cheap, informative summaries of a sequence.
  • A sliding window shows local structure that a single average hides.
  • A FASTA parser needs only a few lines, but production code should use Biopython's SeqIO.

Next: Chapter 1 review