List methods:
>>> a = [66.6,
333, 333, 1, 1234.5]
>>> print
a.count(333), a.count(66.6), a.count('x')
#Think why it printed this way?
>>> a.insert(2,
-1)
>>> a.append(333)
>>> a
#Think why it printed this way?
>>> a.index(333)
1
>>> a.remove(333)
>>> a
[66.6, -1,
333, 1, 1234.5, 333]
>>> a.reverse()
>>> a
#Can you tell the difference between before
and after reverse
>>> a.sort()
>>> a
#Can you tell the difference between before
and after sort
Using Lists as Stacks
>>> stack
= [3, 4, 5]
>>> stack.append(6)
>>> stack.append(7)
>>> stack
#Think why it printed this way?
>>> stack.pop()
7
>>> stack
#Think why it printed this way?
>>> stack.pop()
6
>>> stack.pop()
5
>>> stack
#Think why it printed this way?
Using Lists as Queues
>>> queue
= ["Eric", "John", "Michael"]
>>> queue.append("Terry")
# Terry arrives
>>> queue.append("Graham")
# Graham arrives
>>> queue.pop(0)
'Eric'
>>> queue.pop(0)
'John'
>>> queue
['Michael',
'Terry', 'Graham']
The del statement
>>> a
[-1, 1,
66.6, 333, 333, 1234.5]
>>> del
a[0]
>>> a
#Guess
what happened
>>> del
a[2:4]
>>> a
#Guess
what happened
del can also be used to delete entire variables:
>>> del a
>>> a
#Guess
what will be printed?
Question 1.
>>> l = [1,2,3,4]
>>> l.reverse()
>>> l
#Guess what it will print?
>>> print l
#Guess what it will print?
>>> l = l.reverse()
>>> l
#Guess what it will print? OOPS!!!
>>> l = [2,4,3,1]
>>> l.sort()
>>> l
#Guess what it will print? OOPS!!!
>>> l = l.sort()
>>> l
#Guess what it will print?
>>> print l
#Why the behavior is unexpected?
Dictionaries
>>> tel =
{'jack': 4098, 'sape': 4139}
>>> tel['guido']
= 4127
>>> tel
#Guess what is the output?
>>> tel['jack']
#Guess what is the output?
>>> del
tel['sape']
>>> tel['irv']
= 4127
>>> tel
#Guess what is the output?
>>> tel.keys()
['guido',
'irv', 'jack']
>>> tel.has_key('guido')
#Guess what is the output?
Question 2.
Write three lists of your choice with 5, 6 and 7 elements
respectively.
Assign each of them to the keys "first", "second",
and "third", repectively, in the list_dict, which is an empty dictionary
to begin with.
Now write a function that fetches the n -1 element
of the lists associated with each key.
Try what list_dict.values() return and
what list_dict.items() return.
Now test if a given key exists, if it does what is
the value associated with it.
Format printing:
for x in range(1,11):
print '%2d %3d %4d' % (x,
x*x, x*x*x)
#Think why it printed it this way
Now between each element of the print statment
try inserting \t or \n and see how the behavior changes. These will help
you format the print out.
How do you convert values/numbers to strings? Luckily, Python has a
way to convert any value to a string: pass it to the repr() function, or
just write the value between reverse quotes (``). Some examples:
>>> x = 10
* 3.14
>>> y =
200 * 200
>>> s =
'The value of x is ' + `x`
+ ', and y is ' + `y` + '...' #Watch out for
the reverse quote for x and y
>>> print
s
The
value of x is 31.400000000000002, and y is 40000...
>>> p = [x,
y] # Reverse quotes work on other types besides
numbers:
>>> ps =
repr(p)
>>> ps
'[31.400000000000002,
40000]'
>>> import
math
>>> print
'The
value of PI is approximately %5.3f.' %
math.pi
The value of PI is approximately
3.142.
>>> table
= {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
>>> for
name, phone in table.items():
...
print '%-10s ==> %10d' % (name, phone)
...
Jack
==> 4098
Dcab
==> 7678
Sjoerd
==> 4127
Question 3.
Write three objects - a 6 word string, a 6 item list
and a 6 item dictionary.
Now wrtie a Python script or function(s) that prints
two items (words for strings) of each of the objects on each line, separated
by tabs.
(Hint: use for loops to get the items)
For example:
item1 --> item2
item3 --> item4
item5 --> item6
Also, use the % operator for print formatting.
File objects:
>>> f=open('demo.txt',
'w')
>>> print
f
<open
file '/tmp/workfile', mode 'w' at 80a0960>
>>> f.write(''This
is the first line of file.\n")
>>> f.write(''This
is the second line of file.\n")
>>> f.write(''This
is the last line of file.\n")
>>> f.close()
The rest of the examples in this section will assume that a file object called f has already been created.
To read a file's contents, call f.read(size), which reads some quantity
of data and returns it as a string. size is an optional numeric argument.
When size is omitted
or negative, the entire contents of the file will be read and returned;
it's your problem if the file is twice as large as your machine's memory.
Otherwise, at most size
bytes are read and returned. If the end of the file has been reached,
f.read() will return an empty string ("").
>>> f=open('demo.txt',
'r')
>>> f.read()
#Guess what it will print ?
>>> f.read()
#Guess what it will print ?
f.readline() reads a single line from the file;
a newline character (\n) is left at the end of the string, and is only
omitted on the last line of the file if the file doesn't
end in a newline. This makes the return value unambiguous; if f.readline()
returns an empty string, the end of the file has been reached, while a
blank line is
represented by '\n', a string containing only a single newline.
>>> f.readline()
#Guess what it will print ?
>>> f.readline()
#Guess what it will print ?
>>> f.readline()
#Guess what it will print ?
f.readlines() returns a list containing all the lines of data in the file.
>>> f.readlines()
#Guess what it will print ?
f.write(string) writes the contents of string to the file, returning None.
>>> f.write('This
is a test\n')
The dir() Function
The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:
>>> import string # This is
cery useful modeule
>>> dir(string)
['_StringType', '__builtins__',
'__doc__', '__file__', '__name__', '_float', '_idmap', '_idmapL', '_int',
'_long', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'atof',
'atof_error', 'atoi', 'atoi_error', 'atol', 'atol_error', 'capitalize',
'capwords', 'center', 'count', 'digits', 'expandtabs', 'find', 'hexdigits',
'index', 'index_error', 'join', 'joinfields', 'letters', 'ljust', 'lower',
'lowercase', 'lstrip', 'maketrans', 'octdigits', 'printable', 'punctuation',
'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitfields',
'strip', 'swapcase', 'translate', 'upper', 'uppercase', 'whitespace', 'zfill']
Let's use the string module
An example:
>>> s = "hot cold"
>>> string.upper(s)
HOT COLD
# What you are telling is that take the upper function of string and when
given the arguemnt (s), it
reurns the uppercase of the input string.
>>> string.replace(s, 'cold,
'sold') # To the repalce function of the string module you provide three
arguments, s,
the string, cold,
which is to be replaced with sold.
Ordering French Fries: Place an order, make payment
(which are two arguments), wait (while they dispense or cook (I doubt they
will cookf )resh for you); this is when the function is working), and you
walk away with the Fries.
Think how many lines of code you will have to
write (or set up the whole kitchen ), if you did not have the string module
(or the fast food place). You only need to know what a funciton does. If
you understand it, a single line code, which someone else wrote, is sufficient
to
take your arguement and return you what you asked for. Nice thing is
that you don't even have to understand the GUT of this function (smelling
kitchen). No money here because Python is free.
Try out some more:
Questions 4:
Use the string module to convert the string s = "my
python is cool" to the following: (Hints: capitalize, capwords, replace)
1. "My Python Is Cool"
2. "MY PYTHON IS COOL"
3. "My Python is hot"
Use the string module to count in the string s = "my
python is cool":
1. whitespaces
2. the number of o or py
Use the string module to find the position of 'y' in the string s = "my python is cool":
Use string module to generate a list of words in the string s.
IMPORTNT: The following features/functions/attributes of the string module are very-2 important. Make sure you understand how to use them because they will save you lots of typing and help you avoid reinventing wheels.
'capitalize', 'capwords', 'count', 'find','index','join', 'lower', 'lowercase', 'lstrip', 'replace', 'rstrip', 'split', 'strip', 'swapcase', 'upper', 'uppercase', 'whitespace',
>>> import
sys
>>> dir(sys)
['__name__',
'argv', 'builtin_module_names', 'copyright', 'exit', 'maxint', 'modules',
'path', 'ps1', 'ps2', 'setprofile', 'settrace',
'stderr',
'stdin', 'stdout', 'version']
Without arguments, dir() lists the names you have defined currently:
>>> a = [1,
2, 3, 4, 5]
>>> dir()
#Guess what it will print
Note that it lists all types of names: variables, modules, functions, etc.
dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module __builtin__ :
>>> import
__builtin__
>>> dir(__builtin__)
['AccessError',
'AttributeError', 'ConflictError', 'EOFError', 'IOError', 'ImportError',
'IndexError', 'KeyError', 'KeyboardInterrupt',
'MemoryError',
'NameError', 'None', 'OverflowError', 'RuntimeError', 'SyntaxError', 'SystemError',
'SystemExit', 'TypeError', 'ValueError',
'ZeroDivisionError',
'__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
'compile',
'dir', 'divmod', 'eval', 'execfile', 'filter', 'float', 'getattr', 'hasattr',
'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
'map', 'max',
'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input', 'reduce', 'reload',
'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Now also try: This is the free stuff that you could use as long you know what to inpur and what to expect. Finally, you can undestand some of these by clicking on More on strins, more on lists etc from the web page http://mcdb.colorado.edu/courses/6440/Bioinform_2002.html#Lec1.
>>>
dir("")
#Guess what it will print?
>>>
dir([])
#Guess what it will print?
>>>
dir({})
#Guess what it will print?
>>>
dir(file)
#Guess what it will print?