Python for Finance: Analyze Big Financial Data

(Elle) #1

Basic Data Structures


As a general rule, data structures are objects that contain a possibly large number of other


objects. Among those that Python provides as built-in structures are:


tuple

A collection of arbitrary objects; only a few methods available


list

A collection of arbitrary objects; many methods available


dict

A key-value store object


set

An unordered collection object for other unique objects


Tuples


A tuple is an advanced data structure, yet it’s still quite simple and limited in its


applications. It is defined by providing objects in parentheses:


In  [ 37 ]: t   =   ( 1 ,   2.5,    ‘data’)
type(t)
Out[37]: tuple

You can even drop the parentheses and provide multiple objects separated by commas:


In  [ 38 ]: t   =    1 ,    2.5,    ‘data’
type(t)
Out[38]: tuple

Like almost all data structures in Python the tuple has a built-in index, with the help of


which you can retrieve single or multiple elements of the tuple. It is important to


remember that Python uses zero-based numbering, such that the third element of a tuple


is at index position 2:


In  [ 39 ]: t[ 2 ]
Out[39]: ‘data’
In [ 40 ]: type(t[ 2 ])
Out[40]: str

ZERO-BASED NUMBERING

In contrast to some other programming languages like Matlab, Python uses zero-based numbering schemes. For

example, the first element of a tuple object has index value 0.

There are only two special methods that this object type provides: count and index. The


first counts the number of occurrences of a certain object and the second gives the index


value of the first appearance of it:


In  [ 41 ]: t.count(‘data’)
Out[41]: 1
In [ 42 ]: t.index( 1 )
Out[42]: 0

tuple objects are not very flexible since, once defined, they cannot be changed easily.


Lists

Free download pdf