23BIO112 Introduction to Biological Data
Lab sheet 1
BASICS of PYTHON Programming for Bio informatics
Using the Python Shell 1
Output: Print 2
Input: input 2
Mathematical Operations 2
Code indentation in Python 4
Data Structures 4
Sequence 4
Strings 4
String Manipulation 5
Methods Associated with Strings 5
Lists 7
Tuples 11
Common properties of the sequences 12
Unordered data types 15
Dictionaries 15
Sets 17
Set Operations 18
Reference 20
Using the Python Shell
Line by line execution in an interactive interpreter.
Manjusha Nair M Page 1 of 20
Output: Print
>>> print(’Hello World!’)
Hello World!
>>> print(’Hello’, ’World!’)
Hello World!
>>> print(’Hello’, ’World!’, sep=’;’)
Hello;World!
>>> print("Hello", "World!", sep=";", end=’\n\n’)
Hello;World!
Input: input
>>> name = input("Enter your name: ")
Enter your name: manju
>>> name ’manju’
Mathematical Operations
>>> 1+1
2
When ‘+’ is used on strings, it returns a concatenation:
>>> '1'+'1'
'11'
>>> 'amma'+'mata'
'ammamata'
Note that single (’) and double (") quotes can be used in an indistinct way, as long as they
are used with consistency. That is, if a string definition is started with one type of quote, it
must be finished with the same kind of quote.
Only elements of the same type can be added.
>>>'The Result is : '+str(42)
'The Result is : 42'
>>>'The result is: '+42
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str
Manjusha Nair M Page 2 of 20
>>> 1 + ’1’
Traceback (most recent call last): File "", line 1, in
TypeError: unsupported operand type(s) for +: ’int’ and ’str’
>>> 1 + int(’1’)
2
>>> 12*2
24
>>> 30/3
10.0
>>> 2**8/2+100
228.0
>>> 10/4
2.5
There is also //, which is called floor division, it returns the integer part of the division:
>>> 10//4
2
>>> exit()
Using “String Formatting Operations”
>>> ’The answer is {0}’.format(42)
’The answer is 42’
>>> number = 42
>>> ’The answer is {0}’.format(number) ’
Manjusha Nair M Page 3 of 20
The answer is 42’
>>>count = 5
amount = 45.56
print("count is {0} and amount is {1:9.6f}".format(count, amount))
count is 5 and amount is 45.560000
The first item is count. No format-specifier is specified for count. So the value of
count is simply inserted in the slot indicated by {0}. The second item is amount
and its specifier is 9.6f, which specified the width of the item is 9 and precision is 6.
f means a fixed point number. You can use d for decimal integer and s for a string
Code indentation in Python
Code blocks in Python are defined by indentation. Forcing the programmer to use
indentation is a feature that goes along with one aspect of Python’s design philosophy:
Readability counts.
An Example:
Data Structures
Sequence
Ordered sequence of characters, can be indexed, can be slices, can be iterated
Strings
"This is a string in Python"
’This is a string in Python’
’’’This is a string in Python’’’
"""This is a string in Python"""
Regarding strings enclosed by triple quotes, we can use them to indicate multiline strings
(also known as a block string):
"""Hi! I’m a
Manjusha Nair M Page 4 of 20
multiline
string"""
String Manipulation
Strings are immutable. Once a string is created, it can’t be modified
>>> signal_peptide = ’MASKATLLLAFTLLFATCIA’
signal_peptide is a string that represents an amino-acid sequence.
To get a lower-case version of the string, use the method lower():
>>> signal_peptide.lower()
’maskatlllaftllfatcia’
Despite having obtained the lower-case string, the original string has not been modified:
>>> signal_peptide
’MASKATLLLAFTLLFATCIA’
If we want this new lower case string to have the same name as the previous one, we need
to assign it:
>>> signal_peptide = signal_peptide.lower()
>>> signal_peptide
’maskatlllaftllfatcia’
Methods Associated with Strings
Q1: Convert a DNA sequence into an mRNA sequence
Hint: Use replace()
>>> dna_seq = ’GCTAGTAATGTG’
>>> m_rna_seq = dna_seq.replace(’T’,’U’)
>>> m_rna_seq
’GCUAGUAAUGUG’
replace(old,new[,count]): Allows us to replace a portion of a string (old) with another
(new). If the optional argument count is used, only the first count occurrences of old will
be replaced:
Q2: Calculate the percentage of GC content in a DNA sequence
Manjusha Nair M Page 5 of 20
>>> dna_seq
’GCTAGTAATGTG’
>>> c = dna_seq.count("C")
>>> g = dna_seq.count("G")
>>> (c+g)/len(dna_seq)*100
41.66666666666667
count(sub[, start[, end]]): Counts how many times the substring sub appears, between
the start and end positions (if available).
Q3: Find whether a start codon is present in mRNA sequence
>>> m_rna_seq
’GCUAGUAAUGUG’
>>> m_rna_seq.find(’AUG’)
7
find(sub[,start[,end]]): Returns the position of the substring sub, between the start and
end positions (if available). If the substring is not found in the string, this method returns
the value -1:
>>> m_rna_seq.find(’GGG’)
-1
index(sub[,start[,end]]): Works like find().
Split and join
split([sep [,maxsplit]]): Separates the “words” of a string and returns them in a list. If a
separator (sep) is not specified, the default separator will be a white space:
>>> "Alex Doe,5555-2333,nobody@[Link]".split()
[’Alex’, ’Doe,5555-2333,nobody@[Link]’]
>>> "Alex Doe,5555-2333,nobody@[Link]".split(",")
[’Alex Doe’, ’5555-2333’, ’nobody@[Link]’]
join(seq): Joins the sequence using a string as a “glue character”:
Manjusha Nair M Page 6 of 20
’;’.join([’Alex Doe’, ’5555-2333’, ’nobody@[Link]’])
’Alex Doe;5555-2333;nobody@[Link]’
To join a sequence without any glue character, use empty quotes (""):
>>> ’’.join([’A’,’C’,’A’,’T’])
’ACAT’
Lists
A list is an ordered collection of objects. It is represented by elements separated by
commas and enclosed between square brackets.
Lists are mutable.
>>> first_list = [1, 2, 3, 4, 5]
>>> other_list = [1, ’two’, 3, 4, ’last’]
A list can even contain another list:
>>> nested_list = [1, ’two’, first_list, 4, ’last’]
>>> nested_list
[1, ’two’, [1, 2, 3, 4, 5], 4, ’last’]
An empty list is defined with empty brackets:
>>> empty_list = []
built-in function list():
>>> aseq = "atggctaggc"
>>> list(aseq)
[’a’, ’t’, ’g’, ’g’, ’c’, ’t’, ’a’, ’g’, ’g’, ’c’]
Accessing List Elements
>>> first_list = [1, 2, 3, 4, 5]
>>> first_list[0]
1
>>> first_list[1]
Manjusha Nair M Page 7 of 20
2
>>> first_list = [1, 2, 3, 4, 5]
>>> first_list[-1]
5
>>> first_list[-4]
2
List with Multiple Repeated Items
>>> samples = [’red’] * 5
>>> samples
[’red’, ’red’, ’red’, ’red’, ’red’]
List Comprehension
Comprehension: describing properties shared by its members
>>> a = [0, 1, 2, 3, 4, 5]
>>> [3*x for x in a]
[0, 3, 6, 9, 12, 15]
From a list of strings, let’s make a list with the same elements but without trailing and
leading white spaces:
>>> animals = [’ King Kong’, ’ Godzilla ’, ’Gamera ’]
>>> [[Link]() for x in animals]
[’King Kong’, ’Godzilla’, ’Gamera’]
We can add a conditional statement (if ) to narrow the result set:
>>> animals = [’ King Kong’, ’ Godzilla ’, ’Gamera ’]
>>> [[Link]() for x in animals if ’i’ in x]
[’King kong’, ’Godzilla’]
Modifying Lists
append(element): Adds an element at the end of the list.
>>> first_list.append(99)
>>> first_list
Manjusha Nair M Page 8 of 20
[1, 2, 3, 4, 5, 99]
insert(position,element): Inserts the element element at the position position.
>>> first_list.insert(2,50)
>>> first_list
[1, 2, 50, 3, 4, 5, 99]
extend(list): Extends a list by adding a list to the end of the original list.
>>> first_list.extend([6,7,8])
>>> first_list
[1, 2, 50, 3, 4, 5, 99, 6, 7, 8]
This is the same as using the + symbol:
>>> [1,2,3]+[4,5]
[1, 2, 3, 4, 5]
Removing
pop([index]): Removes the element in the index position and returns it to the point where
it was called. Without parameters, it returns the last element.
>>> first_list
[1, 2, 50, 3, 4, 5, 99, 6, 7, 8]
>>> first_list.pop()
8
>>> first_list.pop(2)
50
>>> first_list
[1, 2, 3, 4, 5, 99, 6, 7]
Manjusha Nair M Page 9 of 20
remove(element): Removes the element specified in the parameter. Unlike pop(), this
function does not return anything.
>>> first_list.remove(99)
>>> first_list
[1, 2, 3, 4, 5, 6, 7]
Trying to remove a nonexistent element raises an error:
>>> first_list
[1, 2, 3, 4, 5, 6, 7]
>>> first_list.remove(10)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: [Link](x): x not in list
del([index] ): Another way of removing an element of a list
del first_list[0]
This has a similar effect to:
first_list.pop(0)
with the difference that pop() returns the extracted element to where it was called, while
del just deletes it.
Copying a List
To copy a list you must use the copy method in the copy module
>>> import copy
>>> a = [1, 2, 3]
>>> b = [Link](a)
There is a way to accomplish the same without using the copy module:
Manjusha Nair M Page 10 of 20
>>> a = [1, 2, 3]
>>> b = a[:]
“=” can be used to copy reference to the original object.
>>> a = [1, 2, 3]
>>> b = a
>>> [Link]()
3
>>> a
[1, 2]
Tuples
Tuples Are Immutable Lists : once created, it cannot be modified.
Tuple’s elements are enclosed between parentheses instead of square brackets.
>>> point = (23, 56, 11)
When the tuple has only one element, you should use a trailing comma:
lone_element_tuple = (5,)
This is done to sort the ambiguity of having (5) that means 5 (number five) since
parentheses around an expression are ignored. With the trailing comma and parentheses
the Python interpreter can tell that it is a tuple and not an expression.
You are not allowed to add or to remove elements from a tuple:
>>> [Link](3)
Traceback (most recent call last):
Manjusha Nair M Page 11 of 20
File "<stdin>", line 1, in ?
AttributeError: ’tuple’ object has no attribute ’append’
>>> [Link]()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: ’tuple’ object has no attribute ’pop’
Common properties of the sequences
Indexing
>>> point = (23, 56, 11)
>>> point[0]
23
>>> sequence = ’MRVLLVALALLALAASATS’
>>> sequence[0]
’M’
>>> parameters = [’UniGene’, ’dna’, ’Mm.248907’, 5]
>>> parameters[2]
’Mm.248907’
>>> point[-1]
11
>>> equence[-2]
’T’
To access an element that is inside a sequence, which is itself inside another sequence,
you need to use another index:
>>> seqdata = (’MRVLLVALALLA’, 12, ’5FE9EEE8EE2DC2C7’)
>>> seqdata[0][5]
’V’
Slicing
You can select a portion of a sequence using slice notation. Slicing consists of using two
indexes separated by a colon (:).
Manjusha Nair M Page 12 of 20
>>> my_sequence="Python"
>>> my_sequence[0:2]
’Py’
When omitting the first sub-index, the index value defaults to the first position
(0):
>>> my_sequence[:2]
’Py’
On the other hand, when the second sub-index is omitted, the index value
defaults to the last position (-1):
>>> my_sequence = "Python"
>>> my_sequence[4:6]
’on’
>>> my_sequence[4:]
’on’
There is a third, optional index to skip positions (step argument):
>>> my_sequence[1:5]
’ytho’
>>> my_sequence[1:5:2]
’yh’
A step with a negative number is used to count backwards. So -1 (in the third
position) can be used to invert a sequence:
>>> my_sequence[::-1]
’nohtyP’
Note that slicing always returns another sequence.
Membership Test
You can verify whether an element belongs to a sequence, using the in keyword:10
>>> point = (23, 56, 11)
>>> 11 in point
True
>>> my_sequence = ’MRVLLVALALLALAASATS’
Manjusha Nair M Page 13 of 20
>>> ’X’ in my_sequence
False
Concatenation
You can concatenate two or more sequences of the same class using the “+” sign:
>>> point = (23, 56, 11)
>>> point2 = (2, 6, 7)
>>> point + point2
(23, 56, 11, 2, 6, 7)
>>> dna_seq = ’ATGCTAGACGTCCTCAGATAGCCG’
>>> tata_box = ’TATAAA’
>>> tata_box + dna_seq
’TATAAAATGCTAGACGTCCTCAGATAGCCG’
Sequences of different types can’t be concatenated:
>>> point + tata_box
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: can only concatenate tuple (not "str") to tuple
len, max, and min
len() returns the length (the number of items) of a sequence:
>>> point = (23, 56, 11)
>>> len(point)
3
>>> my_sequence = ’MRVLLVALALLALAASATS’
>>> len(my_sequence)
19
max() and min() applied over a sequence of numbers return, as expected, the maximum
and the minimum value:
Turn a Sequence into a List
To convert a sequence (like a tuple or a string) into a list, use the list() method:
>>> tata_box = ’TATAAA’
Manjusha Nair M Page 14 of 20
>>> list(tata_box)
[’T’, ’A’, ’T’, ’A’, ’A’, ’A’]
Using a list provides us with methods to indirectly modify a string. Since lists, unlike
strings, are mutable, we can convert a string to a list, modify this list and
then convert it back into a string (with str()).
Unordered data types
Dictionaries
The main characteristic of a dictionary is that it stores arbitrary indexed unordered data
types. It is defined by enclosing is key:value pairs between curly brackets ({}). Only
immutable objects like
strings, tuples and numbers can be used as keys.
>>> iupac = {’A’:’Ala’,’C’:’Cys’,’E’:’Glu’}
>>> print(’C stands for the amino acid {0}’.format(iupac[’C’]))
C stands for the amino acid Cys
A dictionary can also be created from a sequence with dict:
>>> rgb = [(’red’,’ff0000’), (’green’,’00ff00’), (’blue’,’0000ff’)]
>>> colors_d = dict(rgb)
>>> colors_d
{’red’: ’ff0000’, ’blue’: ’0000ff’, ’green’: ’00ff00’}
dict also accepts name=value pairs in the keyword argument list:
>>> rgb = dict(red=’ff0000’, green=’00ff00’, blue=’0000ff’)
>>> rgb
{’blue’: ’0000ff’, ’green’: ’00ff00’, ’red’: ’ff0000’}
Another way to initialize a dictionary is to create an empty dictionary and add elements as
needed:
>>> rgb = {}
>>> rgb[’red’] = ’ff0000’
Manjusha Nair M Page 15 of 20
>>> rgb[’green’] = ’00ff00’
>>> rgb
{’green’: ’00ff00’, ’red’: ’ff0000’}
len(), returns the number of elements in the dictionary:
>>> len(iupac)
3
To add values to a dictionary,
>>> iupac[’S’] = ’Ser’
>>> len(iupac)
4
If you need an ordered dictionary, you must use OrderedDict12:
>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d[’a’] = ’A’
>>> d[’b’] = ’B’
>>> d[’c’] = ’C’
>>> d
OrderedDict([(’a’, ’A’), (’b’, ’B’), (’c’, ’C’)])
Operating with Dictionaries
To get the keys or values of a dictionary, there are methods like keys() and values():
>>> [Link]()
dict_keys([’E’, ’X’, ’C’, ’A’])
>>> [Link]()
dict_values([’Glu’, ’Xaa’, ’Cys’, ’Ala’])
Note that these methods do not return a list (that was their behavior before Python 3), but
they return a special object called dictionary views.
Another way of accessing the elements of a dictionary is by using items(), which returns a
dictionary view with a tuple for every key/value pair:
>>> iupac = {’E’: ’Glu’, ’X’: ’Xaa’, ’C’: ’Cys’, ’A’: ’Ala’}
>>> [Link]()
Manjusha Nair M Page 16 of 20
dict_items([(’E’, ’Glu’), (’A’, ’Ala’), (’C’, ’Cys’), (’X’, ’Xaa’)])
Query Dictionary Values
To query a value from a dictionary without the risk of invoking an exception, use get(k,x).
K is the key of the element to extract, while x is the element that will be returned in case k
is not found as a key of the dictionary.
>>> iupac = {’E’: ’Glu’, ’X’: ’Xaa’, ’C’: ’Cys’, ’A’: ’Ala’}
>>> [Link](’A’,’No translation available’)
’Ala’
>>> [Link](’Z’,’No translation available’)
’No translation available’
Erasing Elements
To erase elements from a dictionary, use the del instruction:
>>> iupac = {’E’: ’Glu’, ’X’: ’Xaa’, ’C’: ’Cys’, ’A’: ’Ala’}
>>> del iupac[’A’]
>>> iupac
{’C’: ’Cys’, ’X’: ’Xaa’, ’E’: ’Glu’}
Sets
A set is a structure frequently found in mathematics. It is similar to a list, with two
outstanding differences: its elements do not preserve an implied order and every element
is unique.
>>> first_set = set()
>>> first_set.add(’CP0140.1’)
>>> first_set.add(’XJ8113.5’)
>>> first_set.add(’EF3616.3’)
>>> first_set
{’CP0140.1’,’XJ8113.5’,’EF3616.3’}
Sets can also be created as
>>> first_set = {’CP0140.1’,’XJ8113.5’,’EF3616.3’}
Manjusha Nair M Page 17 of 20
You can also define a set by comprehension,
>>> {2*x for x in [1,2,3]}
{2, 4, 6}
Since a set does not accept repeated elements, there is no effect when you try to add an
element that is already in the set:
>>> first_set.add(’CP0140.1’)
>>> first_set
{’CP0140.1’,’XJ8113.5’,’EF3616.3’}
In the case of set comprehension:
>>> {2*x for x in [1,1,2,2,3,3]}
{2, 4, 6}
This property can be used to remove duplicated elements from a list:
>>> uniques = {2,2,3,4,5,3}
>>> uniques
{2, 3, 4, 5}
Set Operations
Intersection
>>> first_set = {’CP0140.1’,’XJ8113.5’,’EF3616.3’}
>>> other_set = {’EF3616.3’}
>>> common = first_set.intersection(other_set)
>>> common
Manjusha Nair M Page 18 of 20
{’EF3616.3’}
It is equivalent to &:
>>> common = first_set & other_set
>>> common
{’EF3616.3’}
Union
>>> first_set = {’CP0140.1’,’XJ8113.5’,’EF3616.3’}
>>> other_set = {’AB7416.2’}
>>> first_set.union(other_set)
{’CP0140.1’, ’XJ8113.5’, ’EF3616.3’, ’AB7416.2’}
>>> first_set | other_set
{’CP0140.1’, ’XJ8113.5’, ’EF3616.3’, ’AB7416.2’}
Difference
>>> first_set.difference(other_set)
Manjusha Nair M Page 19 of 20
{’CP0140.1’, ’XJ8113.5’, ’EF3616.3’}
>>> first_set - other_set
{’CP0140.1’, ’XJ8113.5’, ’EF3616.3’}
>>> other_set - first_set
{’AB7416.2’}
Symmetric Difference
>>> first_set.symmetric_difference(other_set)
{’CP0140.1’, ’XJ8113.5’, ’EF3616.3’, ’AB7416.2’}
>>> first_set ^ other_set
set([’EF3616.2’, ’CP0140.1’, ’CP0140.2’, ’EF3616.1’])
Converting a Set into a List
>>> first_set
{’CP0140.1’, ’XJ8113.5’, ’EF3616.3’}
>>> list(first_set)
[’CP0140.1’, ’XJ8113.5’, ’EF3616.3’]
Reference
Python for bioinformatics second edition, chapman & hall/crc, Mathematical and
Computational Biology Series
Manjusha Nair M Page 20 of 20