Practical 2: Common Python Data Structures and Functions
Introduction/Aims of this practical
The aims of this practical are two-fold: firstly to introduce you to the different ways in which data is represented in python, and, in the second part how to use python to manipulate data. This practical is not about modelling per se, but the material here is an essential pre-requisite for the modelling practicals that follow.
Instructions
Having started ScrumPy, read the tutorial material below, and then replicate the python examples in the ScrumPy command window (don't copy and paste!).
It is essential that you understand what each of these examples is doing, it's not enough to simply reproduce the ouptut shown here on your own laptop screens! You should therefore test this by modifying some of these examples - you should be able to correctly predict the effects of these modifications.
Note: In the examples that follow, ">>>" represents the python prompt which tells you that python is ready for you to type something, not something that you should type.
*** more here + exercises without answers + refs to L2 slides ***
Part 1: How data is represented in Python
Data can be as simple as a single digit, or as complex as a suite of genome databases. Python comes with a number of relatively simple data-types, but as we will see, these can be combined to build a python representation of whatever it is that we are studying. The purpose of ScrumPy is to define such collections of simple data-types in a defined way (a data-structure) particularly useful for metabolic modelling, and routines that act upon them. We will start by examining some of the common built-in types.The complete, official python documentation can be found here, although you might find some of it a bit technical, and it goes beyond what is needed for this course.
Viewing data
Simply typing a value at the prompt causes it to be printed on the screen:
if we assign a value to a variable, then typing the variable name will cause the value of the variable to be printed:
Finally, if we use the built in "print" command, this will also cause the value to be printed on the screen. For some data the two methods may result in a different represesentation of the same value:
Question: What is the difference between the two ways in which Greet is represented?
Numbers
Python has four built in ways of defining numbers: integer, long integer, floating point and complex numbers. For our purposes integers can be treated in exactly the same way as long integers, and we will not be considering complex numbers.I
Integers are whole, or counting, numbers and can be either positive or negative, they are represented as a sequence of digits which contains no other characters. Floating-point, or real, numbers contain a fractional component followng a decimal point. They can also be represented using the "e" notation, common to many other languages which represents "times 10 to the power of".
The common mathematical operators (+,-,/,*) work as expected, note that x**y means xy. Numbers can also be compared using the common == (is equal), != (is not equal), < (is less than), <= (is less than or equal to), > (is greater than) and >= (is greater than or equal to). Some of these operators can also be used with othre types of data.
Question: What is the difference between 3/2, 3/2.0 and 3.0/2 ?
Boolean
Booleans are used to indicate whether or not something is considered true, and can take one of exactly two values, True or False, they can be generated explicitly, or as the result of a comparison:
Question: Explain line 6 in the example above.
Strings
Strings are sequences of characters and used to represent arbitrary text. We saw one example in the first section of this practicatal **insert link**. They have many of the same properties as lists and tuples, described below, so we will return to them later.
Lists (and tuples)
Lists and tuples are collections of items in which are stored in a specific order and each item is associated with (indexed by) an integer. The main difference between the two is that tuples are immutable - once a tuple is created it cannot be changed, whereas lists can. For these exercises we will mainly use lists. An empty list can be created by assigning a pair of closed square brackets to a variable.
1 >>> SomeList=[]
Items can be appended to a list by using the append() method.
- A list can also be created and populated in one go.
Or:
Question: What is the item at SomeList[-2] ? SomeList[-4] ?
Indexing can be used to create a copy of part of a subset of a list, a process known as slicing.
The index of a known item can be retrieved using the index() method.
- .
Items can be removed from a list using the remove() method.
Nested lists:
Lists can contain any objects, including other lists. These lists are referred to as nested:
Note the syntax of line 8 above.
Question: Explain the syntax of line 8 - how could you access the item with the value of 3 using this notation?
Tuples
Tuples are very similar to lists, but with one important difference: ince a tuple is defined its contents cannot be changed, they are immutable. Tuples are created in a in the same way as lists, excet the round brackets "()", rather than square brackets "[ ]" are used.
1 >>> SomeTuple = ("Item 1", "Item 2", "Item 3")
Exercise: Repeat the previous list examples with the tuple. What works and what doesnt? Explain.
Strings
Strings are in fact special instance of tuples: they contain only characters, are defined by enclosing them with quote marks, and have some extra methods associated with them specific to text manipulation.
Dictionaries
. Conceptually, dictionaries are quite similar to lists and tuples in that they contain collections of items, however, what makes them distinct is the fact that instead of using integers to refer to items (almost) anything can be used to refer to what is contained, this alos means that, incontrast to lists and tuples there is no implicit order of the items stored in a dictionary. The hace that we can use (almos)t anything to refer to an item gives great flexibilty; dictionaries and "dictianary-like" classes are used extensively in ScrumPy. Dictionaries are created by specifying a sequence of key:value pairs inside a pair of braces "{}":
- As with lists, dictionaries can be nested.
1 >>> dict_1 = {'alfa':1,'beta':2} #define first dictionary
2 >>> dict_2 = {'gamma':1} #define second dictionary
3 >>> dict_1['nested'] = dict_2 #add dict_2 as value to key 'nested' in dict_1
4 >>> dict_1
5 {'beta': 2, 'alfa': 1, 'nested': {'gamma': 1}}
6 >>> dict_1['nested']['gamma'] #access key 'gamma' in nested dictionary
7 1
Part 2: Loops and conditionals
Repetition
For loops
The for loop is used to iterate over an iterable object, e.g. a list. Depending on how the loop is formulated the loop variable will either be an item in the iterable object or an index.
- While loops
while loops continue repeating as long as some condition (the loop invariant) evaluates as True.
1 >>> a_list = ['a','b','c']
2 >>> i = 0 #assign value 0 to variable i
3 >>> while i<len(a_list): #as long as i is less than 3
4 print a_list[i] #print item at index i in a_list
5 i += 1 #increment i by 1
6
7 a
8 b
9 c
10
11
12
13 >>> for i in range(len(a_list)): #iterating over indices
14 print a_list[i]
15
16 a
17 b
18 c
This implies that if the condition i<len(a_list) is never fulfilled the loop continues indefinitely, which it will. Loops can be combined with conditional statements, where a block of code is executed if a statement is true, else another block is executed. The else block is optional, but must be the last option and no statement may follow on the same line.
If several options are possible the elif statement can be used.