Lesson 2 of 8
Module 1 · Python basics
A DNA sequence is just a string of letters, which makes it the perfect way to learn Python's basics. By the end you will have written two small bioinformatics tools.
Strings
Text in quotes is a string. You can measure it, slice it and count letters in it. Python counts positions from 0.
The quotes are what make it a string: "ATG" is three letters of text, while ATG without quotes would be read as the name of a variable. Double and single quotes both work, as long as the pair matches. Counting from 0 means the first letter is at position 0, the second at position 1, and the last letter of a 15-letter string at position 14. Each position is called an index.
In Setting up Python and Jupyter you stored numbers under names; a string is stored the same way, with =. Most of the data you will handle in biology arrives as text first: sequence letters, gene names, sample labels. So the tools in this lesson, measuring, slicing and counting text, are the ones you will reach for most often.
seq = "ATGGCGTACGCTTAG"
print(len(seq), seq[:3], seq.count("G"))seq[:3] takes the first three letters: the start codon, ATG.
What this does
- The first line stores a 15-letter DNA sequence under the name
seq. len(seq)gives the length: the number of letters.seq[:3]is a slice. Square brackets select by position, andstart:stopmeans "from start up to, but not including, stop". With the start left out, Python begins at 0, so this takes positions 0, 1 and 2.seq.count("G")is a method: a function that belongs to a value and is called with a dot after it. It counts how many times G appears.
Reading the output
When print() receives several values separated by commas, it prints them on one line with a space between. So 15 is the length, ATG the slice and 5 the number of Gs, which you can confirm by eye at positions 2, 3, 5, 9 and 14. The "up to but not including" rule has a useful consequence: seq[:3] always has exactly 3 letters, and seq[3:6] would be the next codon. The sequence is 15 letters, five codons, and its last three letters, TAG, are a stop codon.
Python also counts from the end. A negative index starts from the last letter, so seq[-1] is G and seq[-3:] is TAG, the last three letters, whatever the length of the sequence. That is handy for checking that a coding sequence ends in a stop codon without first working out its length.
Strings cannot be changed in place. Writing seq[0] = "C" stops with a TypeError, because a string is immutable: once made, its letters are fixed. Methods such as seq.upper() or seq.replace("T", "U") do not alter seq; they return a new string, which you must store if you want to keep it, for example rna = seq.replace("T", "U"). Forgetting to store the result is a common reason why "nothing happened".
seq[:3] is positions 0, 1 and 2. Schematic, not to scale.Counting from 0, with slices that include the start and leave out the stop, follows an argument made by the computer scientist Edsger Dijkstra in a short 1982 note, "Why numbering should start at zero" (EWD 831): with this rule, the length of seq[a:b] is simply b − a. Biology has no single rule, which matters as soon as you read genome files. GenBank records, GFF annotation files and VCF variant files count the first base as 1 and include both ends of a range. BED files count from 0 and leave out the end, as Python does. When you quote a position, say which convention it uses: off-by-one errors, where a position is wrong by exactly one, are among the commonest bugs in sequence code.
Functions
def defines a function. This one calculates GC content, the share of bases that are G or C. Python uses indentation, four spaces, to show which lines belong to the function.
GC content matters because G pairs with C through three hydrogen bonds, while A pairs with T through two, so GC-rich DNA holds its two strands together more tightly. It affects how primers are designed, how evenly different regions are covered in sequencing, and it differs between genes and between species. A function lets you write the calculation once and then use it on any sequence.
def gc_content(seq):
seq = seq.upper()
return (seq.count("G") + seq.count("C")) / len(seq)
print(round(gc_content(seq), 3))What this does
def gc_content(seq):starts a function calledgc_content. The name in brackets,seq, is its parameter: a placeholder for whatever sequence you hand the function when you use it. The colon at the end says "the body follows".seq = seq.upper()turns the letters into capitals, so lower-case input such as atgc is counted correctly. Sequence files sometimes use lower-case letters for parts of a genome, so this protects against a silent undercount.- The
returnline adds the number of Gs and Cs, divides by the total length, and sends the answer back to whoever called the function. The brackets make sure the addition happens before the division. - The last line, which is not indented, is outside the function. It calls
gc_content(seq)with the 15-letter sequence from above, rounds the answer to three decimal places and prints it.
Reading the output
The sequence has 5 Gs and 3 Cs, so the calculation is (5 + 3) ÷ 15 = 8 ÷ 15 = 0.5333…, shown as 0.533. That is a share between 0 and 1; multiplied by 100, it is 53.3%. Inside the function, seq is a separate, local name: changing it to capitals inside the function does not change the seq you stored outside. One limitation to notice: an empty string has length 0, and dividing by zero stops Python with a ZeroDivisionError. Your own toolkit: modules, files and errors deals with that.
Why write a function at all, when one line would do? Because the same calculation will be needed again, on the next sequence, the next file, the next project. If the formula lives in one place and has a clear name, a fix or an improvement made there reaches every use. A function also documents intent: gc_content(s) says what it computes in a way that a line of counts and division does not.
A frequent mistake is to leave out return. A function without it still runs, but gives back the special value None, Python's word for "no value". If you then try to round or compare the result, you get an error far from the real cause. If a function's result prints as None, check for a missing return first.
Dictionaries and the reverse complement
A dictionary maps keys to values. DNA has two strands, and the other strand reads backwards with each base swapped for its partner: the reverse complement.
The strands read backwards relative to each other because they run in opposite directions, which is called antiparallel. By convention, every DNA sequence is written in the direction its strand is built, from the 5′ end to the 3′ end, so writing the partner strand in that same convention means reversing the order as well as swapping each base. You need this whenever a gene lies on the opposite strand to the one in your file, or when you design a primer that binds the other strand.
complement = {"A": "T", "T": "A", "G": "C", "C": "G"}
def reverse_complement(seq):
return "".join(complement[base] for base in reversed(seq.upper()))
print(reverse_complement("ATGGCGTACG"))
print(sorted(set("ATGGCGTACG"))) # a set keeps each item onceWhat this does
complement = {...}builds a dictionary in curly brackets. Each pair is written key: value, socomplement["G"]looks up the key G and gives back C.reversed(seq.upper())goes through the capitalised sequence from the last letter to the first.complement[base] for base in …takes each of those letters in turn, calls itbase, and looks up its partner."".join(…)glues the partners together into one string. The empty quotes in front mean "put nothing between them";"-".joinwould put a dash between each letter instead.set("ATGGCGTACG")keeps each distinct letter once, andsorted()puts them in alphabetical order as a list.
Reading the output
The first line, CGTACGCCAT, is the reverse complement, checked by hand in the worked example below. The second line is a list, shown in square brackets with each item in quotes: the sequence uses all four bases. This is a quick check for unexpected characters; a sequence containing N or a stray space would show it here. Note that the dictionary has only four keys, so a letter such as N would stop reverse_complement with a KeyError, Python's error for a key that is not in a dictionary. Your own toolkit: modules, files and errors improves this.
Dictionaries are the right tool whenever you look things up by name rather than by position: a base to its partner, a codon to its amino acid, a sample ID to its condition. Looking up a key is fast however large the dictionary grows. Each key can appear only once; if you write the same key twice when building a dictionary, the later value silently replaces the earlier one. That is useful when updating a value, and a trap when two samples accidentally share an ID.
Worked example · check it by hand
each base swapped → CGTACGCCAT
Step by step. Write the ten letters, A T G G C G T A C G, and read them from the right: G C A T G C G G T A. Then swap each letter for its partner, A with T and G with C: G becomes C, C becomes G, A becomes T, T becomes A, and so on along the string, giving C G T A C G C C A T.
What the answer means. It matches the code's output letter for letter, so the function does what you intended. Doing one short case by hand is the simplest test there is. A second check: taking the reverse complement twice must give back the sequence you started with.
Lists, loops and conditions
A for loop repeats code for each item; if and else choose between paths. Here a dictionary holds several sequences.
seqs = {"seq1": "ATGGCGTACGCTTAG", "seq2": "ATATATTTAA", "seq3": "GGCCGCGC"}
for name, s in seqs.items():
gc = gc_content(s)
label = "GC-rich" if gc > 0.5 else "AT-rich"
print(name, round(gc, 2), label)What this does
seqsis a dictionary whose keys are names and whose values are sequences.seqs.items()gives the pairs one at a time, andfor name, s in …unpacks each pair into two names: the key intonameand the sequence intos. The three indented lines run once per pair.gc = gc_content(s)reuses the function you wrote above."GC-rich" if gc > 0.5 else "AT-rich"is a one-line choice: if the condition is true the first value is used, otherwise the second.- The
print()line shows the name, the GC content rounded to two places, and the label.
Reading the output
One line per sequence, in the order they were written in the dictionary. seq1 is the sequence from above, 0.533 rounded to 0.53. seq2, ATATATTTAA, has no G or C at all, so 0 ÷ 10 = 0.0. seq3, GGCCGCGC, is all G and C, so 8 ÷ 8 = 1.0. Watch the boundary: the test is "greater than 0.5", so a sequence with exactly half G and C would be labelled AT-rich. Whether that is right is a decision you make, and should write down, not something Python decides for you.
A list keeps items in order, in square brackets, and you can add to it as you go. That makes a loop and a list a natural pair: start with an empty list and keep the items that pass a test. Here the loop collects the names of the GC-rich sequences.
gc_rich = []
for name, s in seqs.items():
if gc_content(s) > 0.5:
gc_rich.append(name)
print(gc_rich)gc_rich = [] makes an empty list. The if line runs its indented body only when the condition is true, and .append(name) adds one item to the end of the list. seq2 fails the test, so only two names are kept. Unlike a string, a list can be changed in place, which is why append needs no =.
Go deeper: counting k-mers with a dictionary
A k-mer is a short piece of sequence of length k: every overlapping run of k letters. Counting them is an early step in genome assembly and in checking reads for contamination. A dictionary suits the job, with each k-mer as a key and its count as the value. Start with counts = {}, loop over every starting position with for i in range(len(s) - k + 1):, and inside the loop write kmer = s[i:i + k] and then counts[kmer] = counts.get(kmer, 0) + 1. The method get(kmer, 0) returns the stored count, or 0 if the key is not there yet, so the first sighting of a k-mer does not cause a KeyError.
For seq2, "ATATATTTAA", with k = 2, there are 10 − 2 + 1 = 9 overlapping pairs, and the result is {'AT': 3, 'TA': 3, 'TT': 2, 'AA': 1}. The counts add up to 9. The - k + 1 matters: without it, the last slices would be shorter than k letters.
Key point
Indentation is the structure of Python code. If you see IndentationError, check that every line inside a block starts with the same four spaces.
Indentation also changes meaning without any error. In the loop above, if the print() line were moved back to the left edge, it would sit outside the loop: Python would run the loop three times silently and then print only the last sequence, seq3. When results look incomplete, check which lines are indented under which for, if or def.
Further reading · Module 1The Python Tutorial: the official tutorial, for anything you want explained a second way. · All reading for this course
Check your understanding
1. seq = "ATGC" . What is seq[1] ?
2. What is the reverse complement of "AAGC" ?
3. What does set("AATTA") keep?
Up next
Lesson 3
NumPy, pandas and files