Lesson 5 of 14 · 10 min
Lists and Loops
A list is Python's way of keeping many values together inside one named container. In biology this is handy for holding the individual bases of a sequence, or for holding several whole sequences side by side, so you can work through them one item at a time.
Creating a list
bases = ["A", "T", "G", "C"]
print(bases)
print(len(bases))
bases.append("N")
print(bases)
print(bases[0])
print(len(bases))['A', 'T', 'G', 'C']
4
['A', 'T', 'G', 'C', 'N']
A
5
We build a list with square brackets, putting a comma between each item. A value in quotes is a piece of text called a string, and len() is a built-in function that reports how many items the list holds, which is 4 to start. The append() method then adds one new item to the end and changes the list in place, so its length grows to 5. Indexing reads a single item back out by its position, written in square brackets, and Python counts positions starting at 0. That is why bases[0] returns the first item "A", while the appended "N" sits at the last position, bases[4].
Looping with a counter
A for loop repeats the same steps once for every item in a list. Each time round the loop, Python copies the current item into a variable that you name, then runs the indented lines below the colon. To count things while looping, we first make a counter variable and set it to 0, then add 1 to that counter whenever an item meets a condition we care about. The two examples below use this counting pattern: the first walks over single bases, the second over whole sequences.
# count G and C bases in one sequence
sequence = ["A", "T", "G", "C", "G", "G", "A"]
gc_count = 0
for base in sequence:
if base == "G" or base == "C":
gc_count = gc_count + 1
print("GC bases:", gc_count)
# now loop over several records, each a sequence
records = ["ATGC", "GGGCA", "TA", "CCGGTA"]
long_count = 0
for record in records:
if len(record) >= 4:
long_count = long_count + 1
print("Records with 4+ bases:", long_count)GC bases: 4
Records with 4+ bases: 3
In the first loop, gc_count = 0 sets the counter before we start. The line for base in sequence: hands us each base in turn, and if base == "G" or base == "C": tests it: the double equals == checks whether two values are equal, and or makes the whole test true when the base is either G or C. When that is true, gc_count = gc_count + 1 raises the counter by one, so after the loop it holds 4 (the G, C, G and G). The second loop works the same way over whole sequences: len(record) >= 4 is true when a record has four or more bases, where >= means "greater than or equal to", so long_count ends at 3.
Try it yourself: Build a list named sequence holding the ten bases of "ATGCGATTAC", one base per item. Then use a for loop with a counter starting at 0 to count how many bases equal "A", and print the total. Bonus: add a second counter for "T" and print both.