by Megat Harun Al Rashid bin Megat Ahmad
last updated: April 14, 2016
Sequence is a type of data structure. It is similar to array. Each element of a sequence can be accessed according to its index. There are several type of sequences:
The most commonly used is lists, tuples and dictionaries, which we will explored here.
A $list$ can be constructed using the bracket [] with the elements/components of the $list$ separated by commas.
In [1]:
List_num = [1,2,3,4,5]
print List_num
E = len(List_num)
print "There's %d elements in the list %s" % (E,List_num)
Elements in a $list$ can be made of numbers, strings, a mixture of both or other type of sequences. Element can be accessed by specifying the element position in the $list$ (similar to accessing the strings, as discussed in Tutorial 2). The number of elements in $list$ can be known using the $len$() function.
In [2]:
List_str = ["Blythe","Rafa","Felicity","Kiyoko"]
print "What is the word happy in Arabic?"
print "The answer is %s and it's starts with the capital letter %s." % \
(List_str[1],List_str[1][0])
In the above example, the elements in $List$_$str$ $list$ is accessed by specifying the positional index (in square bracket after the variable name of the list) of the $list$ and after that the element of the strings is accessed by specifying a second bracketted index as strings is also a $list$.
Acessed element of a $list$ can be operated (just like variable)
In [3]:
List_mix = ["The Time Machine", 1895, "The Invisible Man", 1897, \
"The Shape of Things to Come", 1933]
print '"%s" was first published in %d with \n"%s" published %d years \
later.' % (List_mix[0],List_mix[1],List_mix[4],List_mix[5]-List_mix[1])
In [4]:
Python_Impl = ['CPython','Cython','PyPy','IronPython','Jython','Unladen Swallow']
New_Python_Impl = [Python_Impl[1],Python_Impl[0],Python_Impl[2]]
print New_Python_Impl
In [5]:
PN = ['Python','Java','C','Perl','Sed','Awk','Lisp','Ruby']
Pyth_ImplN = [PN[2]+PN[0],PN[2]+PN[0][1:],PN[0][:2]*2,\
PN[6][1].upper()+PN[3][2]+PN[0][4:]+PN[0],\
PN[1][0]+PN[0][1:],PN[7][1].upper()+PN[0][-1]+PN[3][-1]+\
PN[1][1]+PN[4][-1]+PN[4][-2]+PN[0][-1]+' '+\
PN[-2][-2].upper()+PN[-3][1]+PN[1][1]+PN[3][3]*2+\
PN[0][-2]+PN[-3][1]]
print Pyth_ImplN
What we have seen are one-dimensional homogeneous and non-homogeneous $lists$.
In [6]:
x = [12,45,78,14,23]
y = ["Dickens","Hardy","Austen","Steinbeck"]
Z = [3E8,'light',"metre"]
$List$ can also be multi-dimensional.
In [7]:
# Homogeneous multi dimensional list (2D):
# List_name[row][column]
x2 = [[12,32],[43,9]]
print x2
print x2[1] # Second row
print x2[0][1] # First row, second column
In a matrix representation, this is: $$\left( \begin{array}{cc} 12 & 32 \\ 43 & 9\end{array} \right)$$
and to get the matrix determinant:
In [8]:
# Matrix determinant
det_x2 = x2[0][0]*x2[1][1]-x2[0][1]*x2[1][0]
print "Determinant of x2 is %d" % det_x2
A multi-dimensional $list$ is actually $lists$ within $list$:
In [9]:
x1 = [0.1,0.2,0.3,0.4,0.5]
x2 = [0,12,34,15,1]
x = [x1,x2]
print x # A 2x5 Array
$List$ can also be non-homogeneous multi-dimensional:
In [10]:
Data_3D = [[[2,3,5],[1,7,0]],[5,"ArXiv"]]
#print number 7
print Data_3D[0][1][1]
print 'Mr. Perelman published the solution \
to Poinc%sre conjecture in "%s".' % (u"\u00E1", Data_3D[1][1])
Data_3D is actually $lists$ inside $lists$ inside $list$ but non-homogeneously.
The elements in the $list$ can be subtituted.
In [11]:
# Extracting and substitution
L1 = Data_3D[0]; print L1
L2 = [Data_3D[1]]+[Data_3D[0][0]]
print L2
print L2[0][1]
Data_3D[1][1] = "PlosOne"
print Data_3D
Iterating on elements in list requires the sequential accessing of the list. This can be done using $for$ and $while$ control structures as well as the $enumerate$() function.
In [12]:
# Looping: for
dwarf = ["Eris","Pluto","Makemake","Haumea","Sedna"]
print dwarf
In [13]:
for name in dwarf:
print name
In [14]:
for z in range(len(dwarf)):
print "%d\t%s" % (z,dwarf[z])
In [15]:
for x,z in enumerate(dwarf,1):
print "%d\t%s" % (x,z)
In [16]:
z = 0
while z < len(dwarf):
print "%d\t%s" % (z+1,dwarf[z])
z = z + 1
In [17]:
x = [12.1,7.3,6.2,9.9,0.5]
y = [4.5,6.1,3.9,1.7,8.0]
i = 0
xy = [] # Creating empty list
while i < (len(x)):
xy = xy + [x[i]*y[i]] # Appending result into list
print '%.1f x %.1f = %.2f' % (x[i],y[i],xy[i])
i = i + 1
print '\n'
print xy
In [18]:
x2 = [[12.1,7.3],[6.2,9.9]]
y2 = [[4.5,6.1],[3.9,1.7]]
j = 0
xy2 = []
xy3 = []
while j < (len(x2)):
k = 0
for k in range(len(x2)):
xy3 = xy3 + [x2[j][k]*y2[j][k]]
print '%.1f x %.1f = %.2f' % (x2[j][k],y2[j][k],xy3[k])
k = k + 1
xy2 = xy2 + [xy3]
xy3 = []
j = j + 1
print '\n'
print xy2
The Gaussian function:$$f(x) = e^{\frac{-(x-\mu)^2}{2\sigma^2}}$$
In [19]:
from math import *
sigma = 0.4
mu = 5.0
x_val = []
ctr = 3
while ctr < 7:
x_val = x_val + [ctr]
ctr = ctr + 0.1
fx = []
for n in range(0,len(x_val),1):
intensity = exp(-(x_val[n]-mu)**2/(2*sigma**2))
fx = fx + [intensity]
print '%f\t%s' % (intensity,int(intensity*50)*'*')
fx
Out[19]:
Each line in a file can be directly converted to a list using the $readlines$() function. For instance, in section 2.4 of tutorial 2, instead of using $read$() function, we can use the $readlines$() function to convert each line in the file $les miserables.txt$ as elements of a list $linecontent$:
In [20]:
# Opening a file
file_read = open("Tutorial2/les miserables.txt")
linecontent = file_read.readlines()
file_read.close()
The elements of $linecontent$ is now the lines in $les miserables.txt$ (including the escape character):
In [21]:
linecontent
Out[21]:
A $tuple$ can be declared using the round bracket. A $tuple$ is actually a $list$ that contains element that cannot be modified or subtituted. Apart from that, its has similar properties with $list$.
In [22]:
t1 = (1,2,3,4)
t1
Out[22]:
Attempting to substitute a $tuple$ element will give an error.
In [23]:
t1[1] = 5
$Dictionaries$ are similar to "associative arrays" in many other programming language. $Dictionaries$ are indexed by keys that can be strings or numbers. Acessing data in $dictionaries$ is by specifying the keys instead of index number. Data can be anything including other $dictionaries$. $Dictionaries$ can be declared by using the curly brackets with the pair of key and data separated by '$:$' and each pair of this element separated by '$,$'.
In [24]:
# Nearby stars to the earth
Stars = {1:'Sun', 2:'Alpha Centauri', 3:"Barnard's Star",\
4:'Luhman 16', 5:'WISE 0855-0714'}
Stars[3] # Specify the key instead of index number
Out[24]:
In the above example the keys are made of integers whereas the data are all made of strings. It can also be the opposite:
In [25]:
# Distance of nearby stars to the earth
Stars_Dist = {'Sun':0, 'Alpha Centauri':4.24, "Barnard's Star":6.00,\
'Luhman 16':6.60, 'WISE 0855-0714':7.0}
print 'Alpha Centauri is %.2f light years from earth.' % \
(Stars_Dist['Alpha Centauri'])
These informations can be made more structured by using $list$ as data in $dictionary$.
In [26]:
# A more structured dictionaries data
Stars_List = {1:['Sun',0], 2:['Alpha Centauri',4.24],\
3:["Barnard's Star",6.00], 4:['Luhman 16',6.60],\
5:['WISE 0855-0714',7.0]}
print '%s is the fourth closest star at about %.2f light \
\nyears from earth.' % (Stars_List[4][0],Stars_List[4][1])
Below is the example of $dictionary$ that contains $dictionary$ type data and the ways to access them.
In [27]:
# Declaring dictionaries data for the dictionary 'Author'
Coetzee = {1974:'Dusklands',
1977:'In The Heart Of The Country',
1980:'Waiting For The Barbarians',
1983:'Life & Times Of Michael K'}
McCarthy = {1992:'All the Pretty Horses',
1994:'The Crossing',
1998:'Cities of the Plain',
2005:'No Country for Old Men',
2006:'The Road'}
Steinbeck = {1937:'Of Mice And Men',
1939:'The Grapes Of Wrath',
1945:'Cannery Row',
1952:'East Of Eden',
1961:'The Winter Of Our Discontent'}
Lewis = {'Narnia Series':{1950:'The Lion, the Witch and the Wardrobe',
1951:'Prince Caspian: The Return to Narnia',
1952:'The Voyage of the Dawn Treader',
1953:'The Silver Chair',
1954:'The Horse and His Boy',
1955:"The Magician's Nephew",
1956:'The Last Battle'
}}
# Assigning keys and data for the dictionary 'Author'
# one of it is a dictionary list
Author = {'South Africa':Coetzee,'USA':[McCarthy,Steinbeck],
'British':Lewis}
In [28]:
Author['South Africa'][1983]
Out[28]:
In [29]:
Author['USA'][1][1939]
Out[29]:
In [30]:
Author['British']['Narnia Series'][1953]
Out[30]:
More on lists and dictionaries can be found on https://docs.python.org/2/tutorial/datastructures.html