Stage 0: Python building blocks
Learn the small pieces everything else is built from: values, lists, dictionaries, libraries and tables.
Every analysis in this guide is made of a few small pieces. In this stage you will meet them one at a time, from the simplest to the most useful, and see how each one leads to the next:
| Step | What it is | Example |
|---|---|---|
| 1. value | One thing: a number, some text, or yes/no. | length = 30 |
| 2. list | Several values in order. | [36, 36, 30, 33] |
| 3. dictionary | Values with names attached. | {"geneA": 36} |
| 4. library | Extra tools other people wrote, such as numpy. | np.mean(lengths) |
| 5. table | Rows and columns, like a spreadsheet (pandas). | genes["length"] |
Step 1: values
A variable is a name that holds a value. The = sign means "store this under that name". Text always goes inside quotes.
gene = "geneC" # text
length = 30 # a whole number
is_long = length > 32 # True or False
print(gene, length, is_long)Step 2: lists
A list holds several values in order, inside square brackets. Counting starts at 0, not 1.
names = ["geneA", "geneB", "geneC", "geneD"]
lengths = [36, 36, 30, 33]
print(names[0]) # the first item
print(lengths[2]) # the third item
print(len(lengths)) # how many itemsStep 3: dictionaries
A dictionary keeps values under names, so you can look things up by name instead of by position. It uses curly brackets { }, with name: value pairs.
length_of = {"geneA": 36, "geneB": 36, "geneC": 30, "geneD": 33}
print(length_of["geneB"])Step 4: libraries
Python on its own is small. A library is a collection of extra tools that other people wrote and shared. You load one with import. Here is numpy, a library for numbers. You do not need to memorise it: just see how it is used.
import numpy as np
lengths = [36, 36, 30, 33]
print(np.mean(lengths)) # the average
print(np.max(lengths)) # the biggest
print(np.sum(lengths)) # the totalStep 5: tables with pandas
pandas is the library for tables. A table is called a DataFrame: rows are things you measured, columns are what you measured about them. Here is a table of four short DNA sequences. Notice that you build it from the lists and dictionaries you just learned.
import pandas as pd
genes = pd.DataFrame({
"gene": ["geneA", "geneB", "geneC", "geneD"],
"sequence": [
"ATGAAATTTAAAGAAATTATTAAAGAAGTTAAAAAA",
"ATGGGCGCCGGCCGCGCCGGGCCCGGCGCCGCCGGC",
"ATGACCGAATGGCTGTAATGCCGTAACGAT",
"ATGGTGCTGAGCCCGGAAGATAAAACCAACGTG",
],
})
genesA new column is just maths on an existing column. Here we count letters, then work out the GC fraction: the share of letters that are G or C.
genes["length"] = genes["sequence"].str.len()
genes["g"] = genes["sequence"].str.count("G")
genes["c"] = genes["sequence"].str.count("C")
genes["gc"] = (genes["g"] + genes["c"]) / genes["length"]
genesTo keep only some rows, put a condition inside square brackets. The condition gives True or False for every row, and only the True rows stay.
genes[genes["gc"] > 0.5]Now practise in Colab
You have read the ideas. Next, try them. The notebook repeats the code above with a few blanks for you to fill in, then ends with small exercises. It is all about this stage. Run the cells in order.
Open the practice notebookYou need a free Google account. When it opens, choose File, then Save a copy in Drive, so your work is yours.
Exercises
These are also in the notebook. Try each one yourself before you open the solution.
Link names to lengths
Show a solution (try it first)
The output should look like this:
30names = ["geneA", "geneB", "geneC"]
lengths = [36, 36, 30]
length_of = {"geneA": 36, "geneB": 36, "geneC": 30}
print(length_of["geneC"])Add a column and filter a table
Show a solution (try it first)
The output should look like this:
gene length codons
0 geneA 36 12.0
1 geneB 36 12.0
3 geneD 33 11.0import pandas as pd
genes = pd.DataFrame({
"gene": ["geneA", "geneB", "geneC", "geneD"],
"length": [36, 36, 30, 33],
})
genes["codons"] = genes["length"] / 3
print(genes[genes["codons"] >= 11])Check your understanding
First star
Using your genes table, what is the GC fraction of geneC, to 3 decimal places?
Stuck? Nudge and solution
Keep the row where gene equals "geneC" and look at its gc column.
print(genes[genes["gene"] == "geneC"]["gc"])Second star
How many of the four genes have a GC fraction above 0.5?
Stuck? Nudge and solution
The filter in the last cell shows exactly those rows. Count them with len(...).
print(len(genes[genes["gc"] > 0.5]))Special thanks to Nilay!