You are on page 1of 29

CSCI 205: Programming

with Databases
Sequences and mappings

First Semester, SY 2021–2022

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 1
Agenda

Lists and tuples Strings Dictionaries

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 2
Lists and tuples

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 3
What are data structures?
• Collection of data elements (numbers,
characters, etc.), the relationships
among them, and operations that can be
applied to them.
• Think of a Jenga tower.
– What is it made of?
– How does its components relate to each other?
– What can you do to the Jenga tower?

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 4
Sequences: lists and tuples
• Most basic Python data structure # Here's a list

• A sequence is a set of elements [3.14, 'hello', "world", 1]

– Each element has a number, which is


its position (index) in the sequence # Here's a tuple
– Sequences can contain other
("where's", 'waldo', 6.3)
sequences

• The most common are lists and


# Here's a list containing a tuple
tuples
– Each element is separated by a comma ['hi', (1, 2, 3), "hello"]
,
– Lists use brackets []
– Tuples, which can't change once
defined, use parentheses ()

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 5
Assignment and indexing
• To access the elements of a # Indexing the zeroth element

sequence, use indexing x = ['a', 'b', 'c']


print(x[0])
– Each element is numbered from 0
upwards [OUT]: 'a'
– You can index a sequence using with the # Nested indexing
index operator [] y = ['a', (5, 6, 7), 'c']
print(y[1][2])
[OUT]: 7

• Be careful when trying to access x[3]


an invalid index. [OUT]: IndexError: list index out of
range

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 6
Visualizing a list
books = ["Harry Potter", "A Game of Thrones", "Ready Player One"]
books à list

0 "Harry Potter"
1 "A Game of Thrones"
2 "Ready Player One"

y = ['a', (5, 6, 7), 'c']


y à list

0 'a'
0 5
1 1 6
2 7
2 'c'

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 7
Indexing and slicing
L[i] element in L at index i x = ['a', 'b', 'c', 'd', 'e']
L[i:j] elements from index i to j-1
L[i:] from index i until the end print(x[2])
L[:j] from the start to index j-1 [OUT]: 'c'
L[-i] element starting from the right print(x[0:2])
(The last element starts at negative index -1)
[OUT]: ['a', 'b']
print(x[2:])
• A helpful rule when indexing: [OUT]: ['c', 'd', 'e']
– The index before the colon is inclusive print(x[:2])
– The index after the colon is exclusive
[OUT]: ['a', 'b']
print(x[-2])
[OUT]: 'd'

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 8
A nifty way to slice sequences
x = ['a', 'b', 'c', 'd', 'e']
• How do you get the last 3
print(x[2:5])
elements of a list?
[OUT]: ['c', 'd', 'e']
– You could do it explicitly

print(x[-3:-1])
– You could use negative indexing [OUT]: ['c', 'd']

– The easiest way to do it is using negative print(x[-3:])


indexing, but leaving out the last index. [OUT]: ['c', 'd', 'e']
• If you want to get the last 3 items, just
use the -3 as the first index.

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 9
Modifying sequences
• Simply index the element of the x = [1, 2, 3]
list you want to change, then x[0] = 'new value'
reassign a value to it. print(x)
– Lists are mutable ("mutate"-able) [OUT]: ['new value', 2, 3]

• This won't work on assigned y = (1, 2, 3)

tuples y[0] = 'new value'


[OUT]: TypeError: 'tuple' object does
– Remember, tuples can't change (they are
not support item assignment
immutable)

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 10
Modifying sequences, continued
• You can also mutate list slices. x = [0, 1, 2, 3, 4]
– Simply get a slice, then assign the x[1:3] = ['a', 'b']
indexed elements with new values
print(x)
[OUT]: [0, 'a', 'b', 3, 4]

• Be sure to mutate the correct x = [0, 1, 2, 3, 4]

number of elements x[1:3] = ['a', 'b', 'c']


print(x)
– You might end up adding more elements
to the list than expected [OUT]: [0, 'a', 'b', 'c', 3, 4]

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 11
Making a copy of sequences
• If you slice a list with no indices, x = [1, 2, 3]
it creates a copy of all the print(x)
elements within the list [OUT]: [1, 2, 3]
– This is useful if you want to make a
copy before performing some
y = x[:]
operations on the given list
– On the right, x and y are now two x[0] = 'new'
different lists print(x)
[OUT]: ['new', 2, 3]

print(y)
[OUT]: [1, 2, 3]

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 12
Making a copy of sequences, continued
• It's important to slice-copy a list x = [1, 2, 3]
versus simply assigning the print(x)
variable to another variable. [OUT]: [1, 2, 3]
– Here, the variable y points to variable x
– Conversely, the variable x points to the y = x
list [1, 2, 3]
x[0] = 'new'
– As such, variable y points to the same
list [1, 2, 3] print(x)
– Therefore, any changes to x are [OUT]: ['new', 2, 3]
reflected on y, as x and y point to the
same list.
print(y)
[OUT]: ['new', 2, 3]

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 13
Sequence operators
• To combine lists, use the (1, 2, 3) + (4, 5, 6)
concatenation operator + [OUT]: (1, 2, 3, 4, 5, 6)
– Be wary: you can only concatenate
sequences of the same type [1, 2, 3] + (4, 5, 6)
[OUT]: TypeError: can only
concatenate list (not "tuple") to
list

• To repeat sequences, use the 'hi' * 3

multiplication operator * [OUT]: 'hihihi'

['hi'] * 3
[OUT]: ['hi', 'hi', 'hi']

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 14
List methods
L.append(x) Add new element x from L x = [3, 2, 1]
L.extend(L2) Appends elements in L2 to x.append(4)
the end of L print(x)
L.sort() Sorts items in L from lowest [OUT]: [3, 2, 1, 4]
to higher
x.extend([5, 6])
L.reverse() Reverses the elements in L
print(x)
[OUT]: [3, 2, 1, 4, 5, 6]
x.sort()
Note: if the list is assigned to a variable, these print(x)
methods modify the list even without [OUT]: [1, 2, 3, 4, 5, 6]
reassigning it to its corresponding variable. x.reverse()
print(x)
[OUT]: [6, 5, 4, 3, 2, 1]

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 15
List methods, continued
L.index(x) Returns the index of the x = [1, 2, 3, 4, 5]
first occurrence of x
print(x.index(4))
L.remove(x) Removes the first
occurrence of x in list L [OUT]: 3
L.insert(x, y) Inserts y into list L at x.remove(3)
index x print(x)
L.clear() Remove all elements
[OUT]: [1, 2, 4, 5]
from L
x.insert(2, 'three')

Note: these methods modify the list even print(x)


without reassigning it to its corresponding [OUT]: [1, 2, 'three', 4, 5]
variable. x.clear()
print(x)
[OUT]: []

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 16
More list operators and functions
X in L Check if value X is in L x = [3, 2, 1]
len(L) Get the number of items in L print(4 in x)
list(string) Converts a string into a list [OUT]: False
of characters
print(len(x))
L1 == L2 Check if the elements in L1
are equivalent to the [OUT]: 3
elements in L2
s = list('hello')
print(s)
[OUT]: ['h', 'e', 'l', 'l', 'o']
t = s[:]
t.reverse()
print(s == t)
[OUT]: False

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 17
Strings

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 18
Strings are just sequences of characters
• Strings act a lot like lists len('python')
– Operators like len(), in, indexing and [OUT]: 6
slicing work as expected
– However, strings are immutable and 'python'[1:3]
cannot be changed
[OUT]: 'yt'

'n' in 'python'

0 1 2 3 4 5 [OUT]: True

p y t h o n p = 'python'
p[0] = 'x'
[OUT]: TypeError: 'str' object does
not support item assignment

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 19
Escape characters
• Sometimes, you want to place print('It\'s game time.')
special characters in string, like [OUT]: It's game time
add in-line apostrophes or force
a next line print('Above.\nBelow.')
[OUT]: Above.
• You can do so using the escape
Below.
character \
– Put a \ before single or double quotes
to make them appear properly in
strings
– Use \n to add a line break

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 20
String methods
S.split() Breaks string S into a list of title = 'hero of time'
words s = title.split()
S.split(x) Breaks string S into a list of print(s)
words, with x specifying the
[OUT]: ['hero', 'of', 'time']
words' boundaries (delimiter)
S.upper() Create a new string from S by
uppercasing every character print(title)
S.lower() Create a new string from S by [OUT]: hero of time
lowercasing every character print(title.upper())
Note: Unlike list methods, string methods are [OUT]: HERO OF TIME
not "in-place"; if the string is bound to a
variable, the variable's value will not change relation = 'son-in-law'
unless the method's result is reassigned to it. print(relation.split('-'))
[OUT]: [son', 'in', 'law']

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 21
String methods, continued
S.find(x) Find the index in S where the s = 'hodgepodge'
first occurrence of x begins
print(s.find('od'))
S.replace( Replaces all occurrences of x
x, y) in S with y [OUT]: 1
S.strip() Removes all whitespace on
the left and right (but not t = s.replace('odge', '')
internally) of string S
print(t)
[OUT]: hp

Note: Unlike list methods, string methods are


not "in-place"; if the string is bound to a u = " give me space "
variable, the variable's value will not change print(u.strip())
unless the method's result is reassigned to it.
[OUT]: give me space

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 22
String formatting
• A frequently used feature in x = 'I\'ve {} and I can\'t get up'
Python programming. y = x.format('fallen')
– Allows you to modify strings at will! print(y)
– Use the format() method to replace [OUT]: I've fallen and I can't get
curly brackets {} in a given string. up.
– You can index the replacements, or
even name them

k = '{name} is {age} years old.' a = '{1}! {2} are {0} running?'


print(k.format(name='Jo', age=24)) b = a.format('you', 'Ahhh', 'Why')
[OUT]: Jo is 24 years old. print(b)
[OUT]: Ahhh! Why are you running?

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 23
Number formatting
• You can format numbers up to a print('{:.3f}'.format(3.1415))
certain precision. [OUT]: 3.142
– This converts the float into a string.
– More can be found here
print('{:.0f}'.format(3.1415))
[OUT]: 3
{:.2f} Format a float to 2 decimal places
{:.0f} Format a float to no decimal places
print('{:.1%}'.format(0.25))
{:.1%} Formats a number to percentage
with 1 decimal place [OUT]: 25.0%
{:,} Format a number with comma
separators print('{:,}'.format(1234))
[OUT]: 1,234

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 24
Advanced formats
• Here's an example that combines p = 'Pi is {pi:.2f}, while '
string formatting by named index e = 'Euler\'s number is {e:.2f}.'
and number formatting. s = p + e
s = s.format(pi=3.1415, e=2.7182)
print(s)
[OUT]: Pi is 3.14, while Euler's
number is 2.72.

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 25
Dictionaries

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 26
Dictionaries
score = {'Alice': 98, 'Beth': 91,
• A dictionary is a mapping. 'Cecil': 93}
– Similar to a list, but…
– Instead of integer indices, a dictionary
has string keys. # Can be formatted as follows
# (for readability):
• Consists of pairs (items) of keys
and their corresponding values score = {
– {key1: value1, k2: v2, ...} 'Alice': 98,
– Keys must be unique within a dictionary. 'Beth': 91,
'Cecil': 93
}

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 27
Dictionary function
score = [
• The dict() function can create a
['Alice', 98],
dictionary from other sequences.
['Beth', 91],
['Cecil', 93]
]

s = dict(score)
print(s)
[OUT]: {'Alice': 98, 'Beth': 91,
'Cecil': 93}

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 28
Operators in dictionaries
s = {'Alice': 98}
• The basic behavior of dictionaries print(s['Alice'])

mirror sequences. [OUT]: 98


s['Beth'] = 91
D[k] Access the value of key k
in D print(s)
D[k] = v Create an item in D with [OUT]: {'Alice': 98, 'Beth': 91}
key k and value v print(len(s))
len(D) Get the number of key- [OUT]: 2
value pairs in D print('Cecil' in s)
k in D Check if a key k is in D [OUT]: False
del D[k] Remove the item in D del s['Beth']
with key k
print(s)
[OUT]: {'Alice': 98}

Department of Information Systems and Computer Science | Loyola Schools | Ateneo de Manila University 29

You might also like