Skip to content
scipython.com

P2.4.5DNA codons

A DNA sequence encodes each amino acid making up a protein as a three-nucleotide sequence called a codon. For example, the sequence fragment AGTCTTATATCT contains the codons (AGT, CTT, ATA, TCT) if read from the first position ("frame''). If read in the second frame it yields the codons (GTC, TTA, TAT) and in the third (TCT, TAT, ATC).

Write some Python code to extract the codons into a list of 3-letter strings given a sequence and frame as an integer value (0, 1 or 2).

Show solution

The following program extracts the codons in the frame specified by frame (0, 1 or 2). After working out where to end the loop over the sequence string, we append the slices of three characters to the codon list.

seq = 'AGTCTTATATCT'
frame = 0       # or 1 or 2

seq_length = len(seq[frame:])
end = seq_length - seq_length % 3

codons = []
for i in range(frame, end, 3):
    codons.append(seq[i:i+3])
print(codons)