Programming & Numerical Analysis: Kai-Feng Chen
Programming & Numerical Analysis: Kai-Feng Chen
PROGRAMMING &
NUMERICAL ANALYSIS2014
Lecture 04:
More on sequence types & data structures
SEQUENCE TYPES:
STRINGS, LISTS AND TUPLES
These sequence types (string, list and tuple) are one of the core
features of python. Very important and extremely useful!
SEQUENCE TYPES
All the sequence types have common characteristics.
Literal values each sequence type has a literal representation:
String uses quotes : 'string' or "string".
tuple uses (): (1,'b',3.1).
list uses []: [1,'b',3.1].
Operations there are three common operations:
+ will concatenate sequences to make a longer one.
* is used with a number to repeat the sequence several times.
[ ] operator is used to select elements.
We will go through these 3 sequence types (in details).
3
STRINGS REVISIT
We have slightly touched strings already in the previous
lectures. But the python strings are much more powerful than that.
fruit
b a n a n a
index = 0
-6
-5
4
-4
-3
-2
-1
STRING METHODS
Similar to functions methods take arguments and returns a
value, but with a slightly different syntax.
Examples:
FIND METHOD
The method find() determines if a specific character/substring
A couple of examples:
>>>
>>>
>>>
1
>>>
2
word = 'banana'
index = word.find('a')
return the index of the first
print index
character found in the string.
word.find('na')
can be a substring rather than a character.
word.find(na)
word.find(na, 3)
name = bob
name.find(b, 1, 2)
the ending index is not
included as well.
THE IN OPERATOR
The find() method should be used only if you need to know the
10
COMPARISON OF STRINGS
The relational operators can be applied to strings as well:
x == y
x != y
x > y
x < y
x >= y
x <= y
These relational operations are based on the standard character-bycharacter comparison rules. For example:
11
COMPARISON OF STRINGS
(II)
Few more string comparison examples:
>>> 'abc' > 'abc'
False
>>> 'abc' > 'Abc'
A has a smaller ASCII code than a.
True
>>> 'abd' > 'abc'
True
>>> 'abcd' > 'abc'
True
>>> 'Abcd' > 'abc'
Its comparing the characters one-by-one
in sequence.
False
12
STRING FORMATTING
One of the important string features is the string formatting. This
The % operator
! '%f' % 1.234567
A couple of common
format symbol:
!
!
!
!
!
!
!
%c!character
%s!string
%d!signed integer
%x!hexadecimal integer
%e!exponential notation
%f!floating point number
%g!the shorter of %f and %e
14
INTERMISSION
Given
>>> fruit = 'banana'
What are the following output?
>>>
>>>
>>>
>>>
>>>
>>>
>>>
>>>
fruit[-0]
fruit[len(fruit)]
fruit[-10:]
fruit[-10]
fruit[3:3]
fruit[:]
fruit[3:10]
fruit[10:]
16
LISTS
A list is also a sequence of values. String contains only characters.
In a list, they can be any type.
18
LIST INDICES
List indices work the same way as string indices:
Any integer expression can be used as an index.
If you try to read or write an element that does not exist, you get
an IndexError.
19
20
LIST METHODS
Just like the strings, python also provides methods that operate on
lists. For example, append() adds a new element to the end,
insert() update the list by inserting the item at the position index.
21
DELETING ELEMENTS
There are several ways to delete elements from a list. If you know the
index of the element you want, you can use pop():
If you know the element you want to remove (but not the index),
you can use remove():
Especially if you want to remove more than one element, you can
use del with a slice index:
FINDING IN LIST
Find the location in a list by index() method:
>>> t = ['a', 'b', 'c']
>>> t.index('b')
1
CONVERTING
STRING TO LIST
The string method split() returns a list of all the words in the
string (splits on all whitespace if left unspecified):
>>>
...
...
...
>>>
>>> s.split()
['Learn', 'from', 'yesterday,', 'live', 'for', 'today,',
'hope', 'for', 'tomorrow.', 'The', 'important', 'thing', 'is',
'to', 'not', 'stop', 'questioning']
26
INTERMISSION
Try this magical way to split and joint the strings:
>>> text = 'Englert-Brout-Higgs-Guralnik-Hagen-Kibble'
>>> l = text.split('-')
>>> l
['Englert', 'Brout', 'Higgs', 'Guralnik', 'Hagen', 'Kibble']
>>> '/'.join(l)
What do you find here? Whats the easiest way to get a single
spaceless string, e.g.
EnglertBroutHiggsGuralnikHagenKibble?
27
INTERMISSION (II)
What will happen if you try to append a list to itself?
>>> t = ['a', 'b', 'c']
>>> t.append(t)
Try to do it and see what you find.
28
FUNCTIONAL
PROGRAMMING TOOLS
There are three built-in functions that are very useful when used
with lists: filter(), map(), and reduce().
29
FUNCTIONAL
PROGRAMMING TOOLS (II)
map(function, sequence) calls function(item) for each of the
sequences items and returns a list of the return values. For
example:
>>>
...
...
>>>
[1,
>>>
...
...
>>>
[3,
def cube(x):
return x*x*x
map(cube, [1,2,3,4,5,6,7])
8, 27, 64, 125, 216, 343]
def add(x, y):
return x+y
map(add, [1,2,3], [2,3,4])
5, 7]
30
FUNCTIONAL
PROGRAMMING TOOLS (III)
reduce(function, sequence) returns a single value constructed by
calling the binary function function on the first two items of the
sequence, then on the result and the next item, and so on.
a
b
banana
banana
a
or b
banana
To check whether two variables (a,b) refer to the SAME object, one
can use the is operator (while the regular == operator check the
contents).
>>> a is b
same object
True
>>> a == b
same content
True
32
a
b
[1,2,3]
[1,2,3]
In this case we would say that the two lists are equivalent, but not
identical, because they are not the same object.
33
ALIASING
If a refers to an object and you assign b = a, then both variables
refer to the same object:
>>> a = [1,2,3]
>>> b = a
>>> a is b
True
a
b
[1,2,3]
TUPLES
A tuple is a sequence of values. The values can be any type, and
they are indexed by integers, so the tuples are a lot like lists.
TUPLE (II)
Most list operators also work on tuples. The bracket operator
indexes an element as usual:
You cant modify the elements of a tuple, but you can replace one
tuple with another:
>>> t[0] = 'A'
TypeError: 'tuple' object does not support item assignment
TUPLE ASSIGNMENT
You already saw the tuple assignment before:
def fib(n):
"""Print a Fibonacci series up to n."""
a, b = 0, 1
here
while a < n:
print a,
a, b = b, a+b
here as well!
a, b = b, a
Tuple assignment is much more elegant!
37
TUPLES AS
RETURN VALUES
A function can only return one value, but if the value is a tuple,
the effect is the same as returning multiple values.
>>> t = divmod(7,3)
>>> t
(2, 1)
>>> quot, rem = divmod(7,3)
>>> print 'quotient =',quot,'and remainder =',rem
quotient = 2 and remainder = 1
When coding for your own function you
just need to do something like return a, b
38
DICTIONARIES
Again a dictionary is similar to a list, but more general.
Indices have to be integers in lists; in a dictionary they can be
(almost) any type (which are called keys).
DICTIONARIES (II)
The in operator works on dictionaries; it tells you whether
something appears as a key in the dictionary:
REVERSE LOOKUP
Lookup: given a dictionary d and a key k, it is easy to find the
corresponding value v = d[k].
INTERMISSION
42
INTERMISSION
Try to run this:
non = ['song','game','challenge','dream','sacrifice']
act = ['sing','play','meet','realize','offer']
for n,a in zip(non,act):
print 'Life is a %s - %s it.' % (n,a)
What do you see? Please also attach the missing last line
Life is love - enjoy it. to the end.
HANDS-ON SESSION
Practice 1:
e
e
e
e
e
e
e
e
e
e
e
e
e
e
44
=
2.72
=
2.718
=
2.7183
=
2.71828
=
2.718282
=
2.7182818
=
2.71828183
=
2.718281828
=
2.7182818285
=
2.71828182846
=
2.718281828459
=
2.7182818284590
= 2.71828182845905
= 2.718281828459045
HANDS-ON SESSION
Practice 2:
3.141592653589793238462643383279502884197169399375105
82097494459230781640628620899862803482534211706798214
80865132823066470938446095505822317253594081284811174
50284102701938521105559644622948954930381964428810975
66593344612847564823378678316527120190914564856692346
0348610454326648213393607260249141273
45
HOMEWORK #4
Exercise 1:
Exercise 2: