IT 116: Introduction to Scripting
Class 23
Review
New Material
Microphone
Graded Quiz 9
You can connect to Gradescope to take weekly graded quiz
today during the last 15 minutes of the class.
Once you start the quiz you have 15 minutes to finish it.
Solution to Homework 9
I have posted a solution to homework 9
here.
Let's take a look.
Homework 11
I have posted homework 11
here.
It is due this coming Sunday at 11:59 PM.
This is the last homework assignment.
Announcement
The UMB IT Club and Boston Linux User Group
will hold a Linux InstallFest on Saturday, May 3rd, from
9 to 5 in the McCormack Conference Room, M03-0721.
If you have a machine on which you would like to install Linux
and would like some help in doing this,
bring it the InstallFest.
Volunteers from the Boston Linux User Group with be on hand
to help with the installation.
They will also help you install the Window Subsystem for Linux
(WSL) on your machine or install Linux as a dual boot.
You can also bring your questions about Linux or Unix to
the InstallFest.
The Boston Linux and Unix User Group counts among its members
some of the most knowledgeable Linux and Unix people in the
Boston area.
You will find directions to M03-0721
here.
Questions
Are there any questions before I begin?
Review
Sequences
- Sequences are Python data types
that hold many values
- The values are stored one right after the other in RAM
- Like this
- There are three sequence data types
- Lists are sequences whose values can be changed
- Tuples are sequences that cannot be changed
- Strings are sequences whose elements are characters
Lists
- The values in a list are called
elements
- You can change any value in the list ...
- and change their order
- You can also add and remove items from the list
- We can create a list
literal
by placing values inside square brackets
- There must be a comma between each value
>>> even_numbers = [2, 4, 6, 8, 10]
>>> even_numbers
[2, 4, 6, 8, 10]
- Here is what this looks like in memory
- Lists can contain a value of any type
- Integers
- Floats
- Strings
- Booleans
- Lists can also contain other lists
The list
Function
list
is a conversion function just like int
and
str
list
turns objects that are collections of things into a list
- Strings are sequences of characters in a specific order
list
will work on strings
>>> name = "Glenn"
>>> characters = list(name)
>>> characters
['G', 'l', 'e', 'n', 'n']
Using a for
Loop with Lists
- A
for
loop will work with a list
>>> numbers = [1, 2, 3, 4, 5]
>>>for n in numbers:
... print(n)
...
1
2
3
4
5
- When we loop through a list we are said to
iterate
over that list
- We can also use a
for
loop with strings
>>> team = "Red Sox"
>>> for char in team:
... print(char)
...
R
e
d
S
o
x
>>>
Empty Lists
The len
Function
- The built-in function
len
will return the length of any sequence
>>> even_numbers = [2, 4, 6, 8, 10]
>>> len(even_numbers)
5
>>> len("foo")
Attendance
New Material
Operators That Work on Objects
- Operators
are special characters that perform some action
- Usually the action creates a new value
- Operators work on values that are called
operands
- Every data type has its own set of operators
- For numbers, we have the arithmetic operators
- Sequences have only two operators
Concatenating Lists
- The concatenation operator that works on strings
>>> name = "Glenn" + " " + "Hoffman"
>>> name
'Glenn Hoffman'
- Also works on lists
>>> n1 = [1,2,3]
>>> n2 = [4,5,6]
>>> n1 + n2
[1, 2, 3, 4, 5, 6]
- That's because both strings and lists are sequence data types
- But it only works when both the operands are the same
data type
>>> n1 + name
Traceback (most recent call last):
File "<stdin>", line 1, in Monday
TypeError: can only concatenate list (not "str") to list
The Repetition Operator
- You cannot subtract two list
>>> n2 - n1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'list' and 'list'
- Nor can you divide them
>>> n1 / n2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'list' and 'list'
- But you can use the * on lists
- When you do, the first operand is a list ...
- and the second is an integer
- The result is a new list ...
- containing multiple copies of the elements of the original
list
>>> zeros = [0] * 5
>>> zeros
[0, 0, 0, 0, 0]
>>> numbers = [1, 2, 3] * 3
>>> numbers
[1, 2, 3, 1, 2, 3, 1, 2, 3]
- The repetition operator also works on strings
>>> "Go " * 3
'Go Go Go '
Indexing
- What if we wanted to get the 3rd element in a list?
- We can do this with a
for
loop
- But it is very cumbersome
>>> even_numbers = [2, 4, 6, 8, 10]
>>> count = 0
>>> for n in even_numbers:
... count += 1
... if count == 3:
... third_element = n
...
>>> third_element
6
- There is an easier way
- All elements in a list are arranged in order
- One right after the other
- Each element's place in line can be specified by an integer
- The integer that specifies an element's place is called an
index
- We can get the value of an individual entry by using the
variable that points to the list ...
- followed by the index inside square brackets
[ ]
LIST_VARIABLE[INDEX]
- Unfortunately, index numbers do not start at 1
- Indexes start at 0
- This is called
zero-based indexing
- This means that the first element in a list has an index of 0
- The second has an index of 1
- And so on
- The index of the last element is one less than the length
- To get a particular element we use the [ ] operator
- We put this operator right after the name of the list variable
- The index goes inside the square brackets
>>> even_numbers[0]
2
>>> even_numbers[1]
4
>>> even_numbers[2]
6
- If you use an index that is too big ...
- you will get an
IndexError
exception
>>> even_numbers[5]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Changing Elements Using Indexes
- Lists are said to be mutable
- That means they can be changed
- This is usually done using indexes
- If we have a list of numbers
numbers = [1, 4, 6, 8]
- We can change the first number like this
>>> numbers[0] = 2
>>> numbers
[2, 4, 6, 8]
- We can use indexes in a
for
loop ...
- to change every element in a list
>>> for i in range(len(numbers)):
... numbers[i] += 1
...
>>> numbers
[3, 5, 7, 9]
Using range with Indexes
- If you need to change every element in a list ...
- you need
for
loop where the loop variable ...
- gets every possible index value
- We can create this list of indexes uding range
- When we call range with 1 argument ...
- it gives you a list of integers starting with 0 ...
- and ending with 1 less than the value of the argument
- I told you this strage behavior had a reason
- The reason is that if we call range
with the length of the array as it's argument ...
- it will generate all the indexes of that array
- Here is an example
>>> nums = [1,2,3,4,5]
>>> for index in range(len(nums)):
... print("index", index)
... print("nums[index]", nums[index])
...
index 0
nums[index] 1
index 1
nums[index] 2
index 2
nums[index] 3
index 3
nums[index] 4
index 4
nums[index] 5
- If we want to change all the numbers in a list by adding 1 ...
- we need a
for
loop using range
to create the indexes
>>> nums
[1, 2, 3, 4, 5]
>>> for index in range(len(nums)):
... nums[index] += 1
...
>>> nums
[2, 3, 4, 5, 6]
- Remember that
nums[index] += 1
means
nums[index] = nums[index] + 1
Slices
- Let's say we define the following list
>>> days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
- What if I wanted to create a new list with just weekdays?
- That is, all the days except Sunday and Saturday
- Python gives us a easy way to do this using a
slice
- A slice is new, smaller, list created from another list ...
- by selecting certain index values
- To create a slice you use the following format
LIST_VARIABLE[FIRST_INDEX:ONE_MORE_THAN_LAST_INDEX]
- So you need to have two indexes to create a slice
- The first index is the index in the original list ...
- of the element you want to be first in the new list
- The second index is trickier
- The second index is not the index of the last element ...
- in the original list
- Its the index of the element after the last element you want
- Let's say we wanted to create a new list weekdays
- The first element we want in our slice is "Monday"
- Which has an index of 1 in the original list
- The last element we want is "Friday"
- Which has an index of 5 in the original list
- Adding 1 to 5 we get 6
- So we create our new list like this
>>> weekdays = days[1:6]
>>> weekdays
['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday']
- Here is another list
>>> digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- To get a slice from 2 to 8 we would write
>>> digits[2:9]
[2, 3, 4, 5, 6, 7, 8]
Leaving Out Indexes in a Slice
- Python allows you to create a slice using only one index
- If you leave out the first index ...
- Python assumes the value is 0
- In other words, the index of the first element
>>> days
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
>>> days[:4]
['Sunday', 'Monday', 'Tuesday', 'Wednesday']
>>> digits
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> digits[:5]
[0, 1, 2, 3, 4]
- If you leave out the second index ...
- Python uses the length of the list
- Which is one more than the index of the last element
>>> days[4:]
['Thursday', 'Friday', 'Saturday']
>>> digits[5:]
[5, 6, 7, 8, 9]
- You can even leave out both indexes ...
- as long as you keep the :
- In this case Python will return a slice that consists of the entire list
>>> days[:]
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
>>> digits[:]
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
- This is a great way to make a copy of a list
>>> daynames = days[:]
>>> daynames
['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
Skipping Elements in a Slice
- You can also skip elements when creating a slice
- It works just like the 3rd argument to the
range
function
- To use this feature you add a second : ...
- followed by an integer
LIST_VARIABLE[FIRST_INDEX:ONE_MORE_THAN_LAST_INDEX:STEP_VALUE]
- The STEP_VALUE works just like in the
range
function
- It is what we add to the index of the previous element ...
- to get the index of the next element
- It is the difference between the index of any two elements ...
- in the original list
- If we wanted to create a slice of all the even digits ...
- we could do it like this
>>> digits = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> digits[0:9:2]
[0, 2, 4, 6, 8]
- Actually, I could leave out the second index
>>> digits[0::2]
[0, 2, 4, 6, 8]
- And even the first
>>> >>> digits[::2]
[0, 2, 4, 6, 8]
The in
Operator
- Operators are special characters that perform some action
- The only operator we have seen so far have been symbols
- But operators can also be words
in
is an operator that works on objects ...
- that are a collection of values
- We use it like this
VALUE in LIST
- The
in
operator returns True
if the
LIST contains VALUE
- Otherwise it returns
False
>>> digits
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
>>> 1 in digits
True
>>> 11 in digits
False
- Is is possible for a list to contain the same value many times
>>> l = [1, 2, 3, 3, 3, 4, 5, 6]
in
will tell you that value is in a list
>>> 3 in l
True
- But it will not tell you it is in there more than once
List Methods
- Lists are objects
- Objects usually have functions that work on the values ...
- inside the object
- These functions are called
methods
- Here are some of the more useful list methods
Method | Description |
append(item) |
Adds item to the end of the list |
pop(index) |
Removes the element at a given index from the list and returns the
value. If called with no argument, it returns the last element and
deletes it from the list.
|
index(item) |
Returns the index of the first element whose value is equal to
item. A ValueError exception is raised
if item is not found in the list.
|
insert(index, item) |
Inserts item into the list at the specified index.
When an item is inserted into a list, the list is expanded in size
to accommodate the new item. The item that was previously at the
specified index, and all the items after it,
are shifted by one position toward the end of the list.
|
remove(value) |
Removes the first element with the value given as a
parameter
|
sort() |
Sorts the items in the list so they appear in ascending order
(from the lowest value to the highest value)
|
reverse() |
Reverses the order of the items in the list |
The append Method
- The append method adds a value ...
- to the end of a list
- It takes one argument, the value you want to add
- Is it probably the most frequently used list method
- You can use the append method to create a list from
scratch
- First you create an empty list
>>> teams = []
>>> teams
[]
- Then we can call the append method on this list
using dot notation
>>> teams.append("Red Sox")
>>> teams
['Red Sox']
- We can call this method as many times as we like
>>> teams.append("Orioles")
>>> teams.append("Blue Jays")
>>> teams.append("Rays")
>>> teams.append("Yankees")
- Each new value is added to the end of the list
>>> teams
['Red Sox', 'Orioles', 'Blue Jays', 'Rays', 'Yankees']
The pop Method
- The pop method does two things
- Removes an element from a list
- Returns the value of that element
- Its argument is the index of the value to be removed
>>> numbs = [1, 2, 3, 4, 5]
>>> n = numbs.pop(0)
>>> n
1
>>> numbs
[2, 3, 4, 5]
- If you leave out the index argument ...
- pop removes the last element
>>> n = numbs.pop()
>>> n
5
>>> numbs
[2, 3, 4]
The index Method
- The
in
operator will tell us if a list contains a value
- But it won't tell us where that value is inside the list
>>> "Red Sox" in teams
True
- We can use the index method to do that
- The argument to index is the value we are
looking for
- It will return the index of that value
>>> teams.index("Red Sox")
0
>>> teams.index("Blue Jays")
2
- If the value we are looking for is not in the list
- We will get a ValueError exception
>>> teams.index("Mets")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: 'Mets' is not in list
- If the value occurs more than once
- The index of the first element is returned
>>> >>> l = [1, 2, 3, 3, 5]
>>> l.index(3)
2
The insert Method
- append always adds to the end of a list
- To insert a value somewhere else we need insert
- The method takes two arguments
- The index where the element should be inserted
- The value to be inserted there
- insert puts the value at the index given ...
- and moves every element to its right over one position
>>> l1 = [1, 2, 3, 4, 5]
>>> l1.insert(2, 7)
>>> l1
[1, 2, 7, 3, 4, 5]
The remove Method
- We can remove an element with a specific value ...
- using the remove method
>>> l1 = [1, 2, 3, 4, 5]
>>> l1.remove(5)
>>> l1
[1, 2, 3, 4]
- If the value occurs more than once ...
- only the first value wil be removed
>>> l2 = [1,2,3,1,2,3]
>>> l2.remove(1)
>>> l2
[2, 3, 1, 2, 3]
The sort Method
- A list is mutable so we can add elements or remove them
- But we can also change the order of the elements
- This can be done with the sort method which takes no argument
>>> l2 = [9, 1, 0, 2, 8, 6, 7, 4, 5, 3]
>>> l2
[9, 1, 0, 2, 8, 6, 7, 4, 5, 3]
>>>l2.sort()
>>> l2
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
The reverse Method
- The reverse method reverses the order of a list
>>> l3 = [5, 4, 3, 2, 1]
>>> l3.reverse()
>>> l3
[1, 2, 3, 4, 5]
>>> l3.reverse()
>>> l3
[5, 4, 3, 2, 1]
- If you want to sort a list in descending order
- You first need to use sort
>>> l4 = [2, 5, 9, 1, 8, 6, 3, 7, 4]
>>> l4.sort()
>>> l4
[1, 2, 3, 4, 5, 6, 7, 8, 9]
- Then use reverse
>>> l4.reverse()
>>> l4
[9, 8, 7, 6, 5, 4, 3, 2, 1]
The del
Statement
- List methods aren't the only things you can use to work with lists
- You can delete elements from a list using the
del
statement
- The format of a del statement looks like this
del LIST_VARIABLE[INDEX]
- After the keyword
del
comes the list variable ...
- and the index of the value to be removed ...
- inside square brackets
-
>>> l5 = [0, 1, 2, 3, 4, 5]
>>> del l5[2]
>>> l5
[0, 1, 3, 4, 5]
The min and max Functions
Fairness
Class Exercise
Class Quiz