Isom Python
Isom Python
Hongchuan Shen
Faculty of Business Administration
University of Macau
1
Learning Outline
• Strings • Dictionaries in Python
• String Literals • Dictionary Operations
• Indices and Slices of Strings • The dict Function
• Python String Methods • Dictionary-Valued Diction
• aries
Lists in Python
• Dictionary Applications
• List Operations
• Dictionary Passing as by
• The split and join Methods Value / Reference
• Slices of Lists
• Tuple in Python
• Nested Lists
• List Operations
• Passing by Value and Referen
ce
2
Strings
• The most common types of data
processed by Python are:
• strings and numbers.
• Examples of Strings:
• Sentences, phrases, words, letters of the
alphabet, names, telephone numbers,
addresses, and social security
3
String Literals
• A string literal is a sequence of characters that is
treated as a single item.
• The characters in strings can be any characters
found on the keyboard and many other special
characters.
• In Python programs, string literals are written as
a sequence of characters surrounded by either
single quotes (') or double quotes ("). Some
examples of strings are as follows:
• "John Junior"
• ‘E22 Avenida de Universidade’
• '76'
• “Hello World!"
4
String Literals
• A string can span multiple lines by using
either three single or double quote
characters to enclose the sequence of
characters, just like multi-line comments.
5
String Literals
• Adjacent strings on the same line will be
silently combined by the Python
interpreter:
6
Indices and Slices of Strings
• In Python, the position or index of a
character in a string is identified with one
of the numbers 0, 1, 2, 3, . . . .
• For instance, the first character of a
string is said to have index 0, the second
character is said to have index 1, and so
on.
• If str1 is a string variable or literal, then
str1[i] is the character of the string
having index i.
7
Indices of Strings
• For instance:
H A M S & E G G S
0 1 2 3 4 5 6 7 8 9 10
-11 -10 -9 -8 -7 -6 -5 -4 -3 -2 -1
8
Slices of Strings
• A substring or slice of a string is a sequence of
consecutive characters from the string.
• For instance, consider the string “Just a
moment”.
• The substrings “Jus”, “mom”, and “nt” begin at
positions 0, 7, and 11, and end at positions 2, 9,
and 12, respectively.
• If str1 is a string, then str1[m:n] is the substring
beginning at position m and ending at position n
- 1.
• Note: If m n, the value of str1[m:n] will be an
empty string (""), the string with no characters.
9
Slices of Strings
• Examples of Slicing a String:
10
Indices on Slices Operations
0 1 2 3 4 5 6 7 8 9
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 Location of pointers
for indices operations
A N A L Y S T I C S
0 1 2 3 4 5 6 7 8 9
Location of pointers
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 for slices operations
Location of pointers
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1
for slices operations
reversely
11
Indices on Slices Operations
12
Indices on Slices Operations
13
Python String Methods
Method Description
capitalize() Converts the first character to upper case
casefold() Converts string into lower case
center() Returns a centered string
Returns the number of times a specified value
count()
occurs in a string
encode() Returns an encoded version of the string
Returns true if the string ends with the
endswith()
specified value
expandtabs() Sets the tab size of the string
Searches the string for a specified value and
find()
returns the position of where it was found
14
Python String Methods
Method Description
format() Formats specified values in a string
format_map(
Formats specified values in a string
)
Searches the string for a specified value and
index()
returns the position of where it was found
Returns True if all characters in the string are
isalnum()
alphanumeric
Returns True if all characters in the string are
isalpha()
in the alphabet
Returns True if all characters in the string are
isdecimal()
decimals
Returns True if all characters in the string are
isdigit()
digits
15
Python String Methods
Method Description
isidentifier() Returns True if the string is an identifier
Returns True if all characters in the string are
islower()
lower case
Returns True if all characters in the string are
isnumeric()
numeric
Returns True if all characters in the string are
isprintable()
printable
Returns True if all characters in the string are
isspace()
whitespaces
Returns True if the string follows the rules of a
istitle()
title
Returns True if all characters in the string are
isupper()
upper case
Joins the elements of an iterable to the end of
join() 16
the string
Python String Methods
Method Description
ljust() Returns a left justified version of the string
lower() Converts a string into lower case
lstrip() Returns a left trim version of the string
Returns a translation table to be used in
maketrans()
translations
Returns a tuple where the string is parted into
partition()
three parts
Returns a string where a specified value is
replace()
replaced with a specified value
Searches the string for a specified value and
rfind()
returns the last position of where it was found
17
Python String Methods
Method Description
Searches the string for a specified value and
rindex()
returns the last position of where it was found
rjust() Returns a right justified version of the string
Returns a tuple where the string is parted into
rpartition()
three parts
Splits the string at the specified separator,
rsplit()
and returns a list
rstrip() Returns a right trim version of the string
Splits the string at the specified separator,
split()
and returns a list
Splits the string at line breaks and returns a
splitlines()
list
18
Python String Methods
Method Description
Returns true if the string starts with the
startswith()
specified value
strip() Returns a trimmed version of the string
Swaps cases, lower case becomes upper case
swapcase()
and vice versa
Converts the first character of each word to
title()
upper case
translate() Returns a translated string
upper() Converts a string into upper case
Fills the string with a specified number of 0
zfill()
values at the beginning
19
Python String Methods
• Examples:
20
Python String Methods
Lists in Python
• Python’s core objects are numbers, strings,
lists, tuples, files, sets, and dictionaries.
• A list is an ordered sequence of Python
objects. The objects can be of any type and do
not have to all be the same type.
• A list is constructed by writing its items
enclosed in square brackets, with the items
separated by commas. Some examples of lists
are
• team = ["Seahawks", 2014, "CenturyLink Field"]
• nums = [5, 10, 4, 5]
• words = ["spam", "ni"]
22
Creating a List
• Specify a list variable with the subscript
operator []
Page 23
Test
24
Lists Vs. Strings
• Both lists and strings are sequences,
and the [] operator is used to access an
element in any sequence
• There are two differences between lists
and strings:
• Lists can hold values of any type, whereas strings are
sequences of characters
• Moreover:
• strings are immutable— you cannot change the
characters in the sequence
• Lists are mutable
Page 25
Using The Square Brackets
• Note that there are two distinct uses of the square brackets.
When the square brackets immediately follow a variable
name, they are treated as the subscript operator:
values[4]
values = [4]
Page 26
Loop Over the Index Values
• Given the values list that contains 10
elements, we will want to set a variable,
say i, to 0, 1, 2, and so on, up to 9
# First version (list index used)
for i in range(10) :
print(i, values[i])
28
List Operations
Function or Description
Method
insert() Adds an element at the specified position
+ Concatenate
* List replication
29
Test
30
The split and join Methods
• The split and join methods are extremely
valuable methods that are inverses of
each other.
• The split method turns a single string into
a list of substrings and the join method
turns a list of strings into a single string.
31
The split and join Methods
• Examples of split:
32
The split and join Methods
• Examples of join:
33
Slices of Lists
• A slice of a list is a sub-list specified with colon
notation.
• It is analogous to a slice of a string.
• Meaning of slice notations:
Slice
Meaning
Notation
list1[m:n] list consisting of the items of list1 having
indices m through n-1
list1[:] a new list containing the same items as
list1
list1[m:] list consisting of the items of list1 from
list1[m] through the end of list1
list1[:m] list consisting of the items of list1 from the
beginning of list1 to the element having 34
index m-1
tuple in Python
• Tuples, like lists, are ordered sequences of
items.
• The main difference between tuples and lists
are that tuples cannot be modified directly.
• Tuples have no append, extend, or insert
methods.
• The other list functions and methods apply to
tuples, and its items can be accessed by
indices.
• Tuples also can be sliced, concatenated, and
repeated.
35
tuple in Python
• Tuples are written as comma-separated
sequences enclosed in parentheses.
• The following two statements used to
define a tuple
t = ('a', 'b', 'c')
t = 'a', 'b', 'c'
• print functions always display tuples
enclosed in parentheses.
36
tuple
Nested Lists
• items also can be lists or tuples. Lists of
tuples play a prominent role in analyzing
data.
• Example:
38
List Operations
• Appending Elements
• Inserting an Element
• Finding an Element
• Removing an Element
• Concatenation
• Equality / Inequality Testing
• Sum, Maximum, Minimum, and Sorting
• Copying Lists
Page 39
Appending Elements
• Sometimes we may not know the values that
will be contained in the list when it’s created
• In this case, we can create an empty list and
add elements to the end as needed
#1
friends = []
#2
friends.append("Harry")
#3
friends.append("Emily")
friends.append("Bob")
friends.append("Cari")
Inserting an Element
• Sometimes the order in which elements
are added to a list is important
• A new element has to be inserted at a specific position
in the list
#1
friends = ["Harry",
"Emily", "Bob",
"Cari"]
#2
friends.insert(1,
"Cindy")
Page 41
Finding an Element
• If you simply want to know whether an element
is present in a list, use the in operator:
if "Cindy" in friends :
print("She's a friend")
Page 42
Removing an Element
• The pop() method removes the element at a
given position
friends = ["Harry", "Cindy", "Emily", "Bob",
"Cari","Bill"]
friends.pop(1)
Page 43
Concatenation
• The concatenation of two lists is a new list that contains the
elements of the first list, followed by the elements of the second
Page 44
Replication
• As with string replication of two lists is a new list that contains the
elements of the first list, followed by the elements of the second
monthInQuarter = [ 1, 2, 3] *
4
• Results in the list [1, 2, 3, 1, 2, 3, 1, 2, 3, 1, 2 ,3]
• You can place the integer on either side of the “*”
operator
• The integer specifies how many copies of the list should
be concatenated
• One common use of replication is to initialize a list with a
fixed value monthlyScores = [0] *
12
Page 45
Equality / Inequality Testing
• You can use the == operator to
compare whether two lists have the
same elements, in the same order.
[1, 4, 9] == [1, 4, 9] # True
[1, 4, 9 ] == [4, 1, 9] # False.
Page 46
Sum, Maximum, Minimum
• If you have a list of numbers, the sum()
function yields the sum of all values in the list.
Page 47
Sorting
• The sort() method sorts a list of numbers
or strings.
values = [1, 16, 9, 4]
values.sort() # Now values is [1, 4 , 9, 16]
Page 48
Copying Lists
• If the variable var1 has a mutable value
(such as a list), a statement of the form
var2 = var1 results in var2 referencing the
same object as var1.
• Any change to the value of var2 affects the
value of var1.
• Objects that can be changed in place are
called mutable, objects that cannot be
changed in place are called immutable.
49
Test
50
Copying Lists
• Consider the following two code segments:
51
List
Passing by Value and
Reference
• Many languages let us define whether
you want to pass an argument by value
or by reference based on the way you
write your function
• The language, like Java and Python,
whether an argument will be passed by
value or by reference is determined in
the language.
• Primitive data types (immutable) like
integers and strings are always passed
by value, while advanced data structures
(mutable) like lists are always passed by53
Passing by Value and
Reference
• Example: passing the data type integer
(by value)
54
Passing by Value and
Reference
• Example: passing the data type string (by
value)
55
Passing by Value and
Reference
• Example: passing the data type list (by
reference)
56
Passing by Value and
Reference
• Example: passing element of data type
integer
57
Passing by Value and
Reference
• Example: passing element of data type
list
58
Passing by Value and
Reference
Dictionaries in Python
• Python dictionary is defined as a
collection of comma-separated pairs of
the form “key:value” enclosed in curly
braces.
• The keys must be immutable objects
(such as strings, numbers, or tuples), but
the values can have any data types. The
keys are unique, but the values needn’t
be unique.
• The value associated with key1 is given
by the expression dictionaryName[key1].
60
Creating Dictionaries
• Suppose you need to write a program
that looks up the phone number for a
person in your mobile phone’s contact
list
• You can use a dictionary where the
names
contacts are keys and
= { "Fred": the"Mary":
7235591, phone numbers
3841212,
are"Bob":
values
3841212, "Sarah": 2213278 }
Page 61
Dictionary Operations
Operation Description
len(d) number of items (that is, key:value pairs)
in the dictionary
63
Dictionary Operations
Operation Description
list(d) returns a list of the keys in the dictionary
64
Dictionary Operations
Operation Description
d.clear() removes all items (that is, key:value
pairs) from the dictionary for k in d:
iterates over all the keys in the
dictionary
d.update(c) merges all of dictionary c’s entries into
dictionary d. If two items have the same
key, the value from c replaces the value
from d
max(d) largest value of d.keys(), provided all
keys have the same data type
65
Accessing Dictionary Values []
• The subscript operator [] is used to return
the value associated with a key
• The statement
# prints 7235591.
print("Fred's number is",
contacts["Fred"])
67
Dictionaries in Python
• Example: (without search fail handler)
68
Dictionaries in Python
• Example: (without search fail handler)
69
Dictionaries in Python
• Example: (retrieval keys, values, and items)
70
The dict Function
• A list of two-item lists or two-item tuples can
be converted to a dictionary with the dict
function.
• For instance if
list1 = [["one", 1], ["two", 2], ["three", 3]]
or
list1 = [("one", 1), ("two", 2), ("three", 3)]
• The value of dict(list1) will be the dictionary
{"one":1, "two":2, "three":3}
71
Adding/Modifying Items
• A dictionary is a mutable container
• You can add a new item using the
subscript operator [] much as you
would with a list
contacts["John"] = 4578102 #1
• To change the value associated with a given key, set a
new value using the [] operator on an existing key:
contacts["John"] = 2228102 #2
Page 72
Test
73
Adding New Elements Dynamically
• Sometimes you may not know which items will be
contained in the dictionary when it’s created
• You can create an empty dictionary like this:
favoriteColors = {}
Page 74
Removing Elements
• To remove an item from a dictionary,
call the pop() method with the key as
the argument:
contacts = { "Fred":
7235591, "Mary":
3841212, "Bob":
3841212, "Sarah":
2213278 }
• This removes the entire item, both the key and its associated value.
contacts.pop("Fred")
Page 75
Removing and Storing Elements
contacts.pop("Fred"
)
Page 76
Test
77
Dictionary Application
• Example: Create Dictionary for Counting
Frequent
78
Dictionary Application
• Example: Create Dictionary for Counting
Frequent
79
Dictionary Application
• Example: Create Dictionary for Counting
Frequent
80
Dictionary Application
• Example: Create Dictionary for Counting
Frequent
81
Dictionary Passing as by
Value / Reference
82
mutable vs immutable