CHAPTER THREE
Sequences
Sequences
• contains objects that are kept in a specific order
• you can identify an object in a sequence by its index location
• the first object in a sequence is zero
• when a sequence is referenced outside its range, an exception is raised
• a variable contains zero or one value
• a sequence can contain zero or many values
• you can extract from a sequence with the slicing operation
• examples of sequences include lists, tuples and strings
Sequences
Operations on sequences
Three common operations applied to sequences
• + will concatenate sequences to make them longer
• * is used with numerical digits to repeat the sequence several times
• [ ] fetches a particular element from the sequence(index) or a subset of
elements (slicing)
Strings (immutable or static )
Definition
• a sequence that contains single-byte ASCII characters
• used to store and represent text information
• can be enclosed in single ('), double (") or triple quotes (''' or """) as follows:
• o = ‘Lets party’ OR o = “Lets party” OR o = '''Lets party'''
• are immutable, cannot modify an existing string object
• an operation on a string object creates a new string object
Strings (immutable or static )
Displaying strings
• newline e.g k="Hello World!\nIt's hot
• continuation e.g k="Hello World!\
It's hot“
• Single quote use escape character e.g k='Isn\'t it?‘
• If double quotes no need for \ e.g k="Isn't it? "
• In a triple quoted string, line breaks in the literal are preserved as newline
characters. You cannot use a backslash in a triple-quoted string
Strings (immutable or static )
How characters are stored in a string
• Example s = “Mi”
• each character is stored at a specific index location
• a character is accessed through the index e.g. s[0] is M
• there is no separate data type for characters
• a character is a string of length 1
Strings (immutable or static )
String methods
• to view a list of all methods
that can be used with str
type help(‘str’)
Strings (immutable or static )
String methods (cont)
Strings (immutable or static )
Finding substrings in a string
• String Methods Used to Find Substrings in a String
Arrays
Numerical arrays
• a string is an array of characters
• a numerical array stores numerical data
• they do not have NULL characters
• numerical arrays are NOT terminated by NULL characters
• indexes are used for accessing elements
• There are one and two dimensional arrays
Arrays
One dimensional array
• given an array p as follows:
• array declaration : p= [ 0 for i in range(5) ]
• input into array : for i in range(5):
p[i]= int(input())
• print array values : for n in p:
print (n)
Arrays
Two dimensional array
• are divided into rows and columns
• The indices of row and column begin at value 0
• To access each element of the array, you have to specify two indices; one for row, and
the other for column
• Both are enclosed in square brackets.
• array declaration : p = [ [ 0 for i in range(3) ] for j in range(3) ]
• input into array : for d1 in range(3):
for d2 in range(3):
p[d1][d2]= int(input()
• print array value : p[1][2]
Lists (mutable)
Definition
• is a container object that is mutable
• is a collection of elements, which might include other lists
• begin and end with a square bracket
• elements inside are separated with commas
• first element of the list is at index 0 last element is at index -1
• Example: [p = ["John", "Kelly", 1, 2, [Sugar, Butter, 10]] #list containing a list
print (p[0]) #prints John
Lists (mutable)
Length of a list
• to find the length of a list, you use the len() function
• it returns the length as an index location of the last element plus one
• Given : names=['John', 'Kelly', 'Caroline', 'Paula']
len(names) will return 4
for i in range(0,len(names)): #range(0,4) returns 0 - 3
print (names[i])
Lists (mutable)
List Slicing
•You can slice a list into parts to get desired elements
Given : names=['John', 'Kelly', 'Caroline', 'Paula']
names[0:3] #returns index 0 to 2 ['John', 'Kelly', 'Caroline']
names[-4] #returns fourth from last ['John']
names[-3:-1]#returns third from last to second from last 'Kelly', 'Caroline']
names[:2] #returns first 2 ['John', 'Kelly']
names[2:] #returns index at 2 to last ['Caroline', 'Paula']
names[:-2] #returns index 0 to second from last ['John', 'Kelly', 'Caroline']
names[-2:] #returns second from last to end of the list ['Caroline', 'Paula']
Lists (mutable)
Other list methods
• some of the methods
that can be applied to lists
Tuples (immutable)
Tuple objects
• are a type of sequence, like strings
• unlike strings, which can contain only characters tuples can contain elements of any type
• a tuple is an immutable object that cannot be changed once created
• as with every sequence, tuple indices are zero based
• the first element is at index 0, and the last element is at index -1
• Is similar to a list, but elements are enclosed in parentheses ()
• the elements are in a defined order
Tuples (immutable)
Tuples vs Lists
• are faster than lists, when an item has to be added on the list a new one is
created
• when defining a constant set of data, a tuple is preferred (write-protected)
• tuples can be used as dictionary keys. Dictionary keys must be immutable
• if tuples contain lists, then they can not be used as dictionary keys
• tuples can be converted into lists and vice versa
Tuples (immutable)
Tuple example
• demonstration of a tuple
names=('John', 'Kelly', 'Caroline', 'Steve', 'Katheline')# declaration
print ("The names in the tuple are:", names) # displayed as declared
print ("The first name in the tuple is", names[0]) # John
print ("The last name in the tuple is", names[len(names)-1])# Katherine
print ("The names in the tuple are")
for n in names:
print (n) # John
Kelly
Caroline
Steve
Katheline
Dictionary (mutable)
Dictionary
• a combination of key/value pairs in which every key has to be unique
• Key/value pairs are separated by a colon, and the pairs are separated by
commas
• The key/value pairs are enclosed in a curly brackets
• Syntax
d = {key1 : value1, key2 : value2 }
• dictionaries are mutable, which means a dictionary can be modified, and
you don’t have to create a copy of it to modify it
• Dictionary keys are case sensitive and immutable because Python
associates them with a unique number called a hash. Also,
• dictionary keys can be of mixed data types: strings, integers, and others.
Dictionary (mutable)
Methods
• a some of the methods that
can be applied to dictionary
Dictionary (mutable)
Example
• illustration of a dictionary
cap={'U.S.':'Washington D.C.','U.K.':'London','India':'New Delhi',}
n=input('Enter country: ')
if n in cap:
print ('The capital of', n , 'is', cap[n])
else:
print ('Sorry the country', n, 'does not exist in our dictionary')
cap['Australia']='Sweden'
print ('The dictionary after adding a country:')
for country, capital in cap.items():
print ('Capital of', country, 'is' , capital)
m=input('Enter the country to delete:')
del cap[m]
print ('The dictionary after deleting a country:')
for country, capital in cap.items():
print ('Capital of', country, 'is' , capital)
Sets (mutable)
The set container
• is an unordered collection of objects that can be contained in a hashtable
• hashtable is a set of key-value pairs
• since the sets are unordered, they do not support slicing or other
sequence-like behaviour
• sets cannot have any duplicate elements
• an element only appears 0 or 1 times
• a set is mutable except a frozenset which is immutable
Sets (mutable)
Uses of sets
• to tests membership
• to remove duplicates from a sequence
• to compute boolean operations like union , intersection, symmetric
difference and set difference
Sets (mutable)
Union (|)
• in a union operation an element appears in the union if it exists in one set
or the other
s1=set([3,5,6,10,11,100])
s2=set([1,3,5,6,11,15])
s1 | s2 s1.union (s2) returns {1,3,5,6,10,11,15,100}
Sets (mutable)
Intersection (&)
• in an intersection operation, the elements that appear in both sets appear
in the intersection
s1=set([3,5,6,10,11,100])
s2=set([1,3,5,6,11,15])
s1& s2 s1.intersection (s2) returns {3,5,6,11}
Sets (mutable)
Difference (-)
• In a difference operation, all the elements that are in the left set but not
in the right set will appear in the difference operation
s1=set([3,5,6,10,11,100])
s2=set([1,3,5,6,11,15])
s1-s2 s1.difference (s2) returns {10,100}
s2-S1 s2.difference (s1) returns {1,15}
Sets (mutable)
Symmetric difference (^)
• is the object that appears in one of the two sets provided but not in both
s1=set([3,5,6,10,11,100])
s2=set([1,3,5,6,11,15])
s1.symmetric_difference (s2) returns {1,10,15,100}
Sets (mutable)
Symmetric difference update
• symmetric_difference_update () method changes the first set to match
the set that is returned by the function
s1=set([3,5,6,10,11,100])
s2=set([1,3,5,6,11,15])
s1.symmetric_difference_update (s2) returns s1 as {1,10,15,100}
Sets (mutable)
Membership
• to check if an object is in the set in is used
s1=set([3,5,6,10,11,100])
s2=set([1,3,5,6,11,15])
10 in s1 returns True
15 in s1 returns False
15 in s2 returns True
Sets (mutable)
Iteration through a set
• makes it easy to iterate through distinct objects e.g
s1=set([3,5,6,10,11,100])
for n in s:
if ((n % 2 ) == 0)
print (“%d is even” %n)
else:
print (“%d is odd” %n)
• Output: 3 is odd
5 is odd
6 is even
10 is even
11 is odd
100 is even
Sets (mutable)
Removing objects from a set
•there are four functions to remove objects from a set
•pop () removes an object from a set. Object to be removed not specified
•remove () removes a specified object from a set
•discard () removes a specified object from a set. No error if object does not exist
•clear () clears the whole set completely
Sets (mutable)
Set methods/functions
• The list of methods and functions that can be applied on a set
Notes