Objects of type list are much more flexible and powerful in comparison to tuple objects.
From a finance point of view, you can achieve a lot working only with list objects, such
as storing stock price quotes and appending new data. A list object is defined through
brackets and the basic capabilities and behavior are similar to those of tuple objects:
In [ 43 ]: l = [ 1 , 2.5, ‘data’]
l[ 2 ]
Out[43]: ‘data’
list objects can also be defined or converted by using the function list. The following
code generates a new list object by converting the tuple object from the previous
example:
In [ 44 ]: l = list(t)
l
Out[44]: [1, 2.5, ‘data’]
In [ 45 ]: type(l)
Out[45]: list
In addition to the characteristics of tuple objects, list objects are also expandable and
reducible via different methods. In other words, whereas string and tuple objects are
immutable sequence objects (with indexes) that cannot be changed once created, list
objects are mutable and can be changed via different operations. You can append list
objects to an existing list object, and more:
In [ 46 ]: l.append([ 4 , 3 ]) # append list at the end
l
Out[46]: [1, 2.5, ‘data’, [4, 3]]
In [ 47 ]: l.extend([1.0, 1.5, 2.0]) # append elements of list
l
Out[47]: [1, 2.5, ‘data’, [4, 3], 1.0, 1.5, 2.0]
In [ 48 ]: l.insert( 1 , ‘insert’) # insert object before index position
l
Out[48]: [1, ‘insert’, 2.5, ‘data’, [4, 3], 1.0, 1.5, 2.0]
In [ 49 ]: l.remove(‘data’) # remove first occurrence of object
l
Out[49]: [1, ‘insert’, 2.5, [4, 3], 1.0, 1.5, 2.0]
In [ 50 ]: p = l.pop( 3 ) # removes and returns object at index
print l, p
Out[50]: [1, ‘insert’, 2.5, 1.0, 1.5, 2.0] [4, 3]
Slicing is also easily accomplished. Here, slicing refers to an operation that breaks down a
data set into smaller parts (of interest):
In [ 51 ]: l[ 2 : 5 ] # 3rd to 5th elements
Out[51]: [2.5, 1.0, 1.5]
Table 4-2 provides a summary of selected operations and methods of the list object.
Table 4-2. Selected operations and methods of list objects
Method Arguments Returns/result
l[i] = x
[i]
Replaces ith element by x
l[i:j:k] = s
[i:j:k]
Replaces every kth element from i to j - 1 by s