IT 116: Introduction to Scripting
Class 23
Review
New Material
Microphone
Questions
Are there any questions before I begin?
No Graded Quiz Next Tuesday
Since there only 1 class this week, there will be no
graded quiz next Tuesday.
There will be a graded the following Tuesday.
It will cover material in Class Notes 23, 24 and 25.
Solution to Homework 9
I have posted a solution to homework 9
here.
Homework 11
I have posted homework 11
here.
It is NOT due this Sunday.
Instead is due the following Sunday, December 6th at 11:59 PM
Graded Quiz Today
After I finish talking I will pass out the papers for
today's graded quiz.
Today's Class
Today I will discuss operators that work on objects,
indexing to change the elements of a list, the range
function and list methods.
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 values 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 ...
- giving each element in order
>>> 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 builtin function
len will return the length of any sequence
>>> even_numbers = [2, 4, 6, 8, 10]
>>> len(even_numbers)
5
>>> len("foo")
The max and min Functions
- If we have a list
nums = [5, -4, 45, 56, 2]
- We can find the largest element using the builtin in function
max
>>> max(nums)
56
- We can find the smallest using the builtin
min
>>> min(nums)
-4
- These functions only work where there is a natural ordering
of the elements
- So we can sort a list that only contains numbers ...
- or only contains string
- But not a list with numbers and strings
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 adds one string to the back of
another
>>> name = "Glenn" + " " + "Hoffman"
>>> name
'Glenn Hoffman'
- But it 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
- If we follow the list variable with square brackets,
[ ] ...
- and put an index inside the brackets ...
- we will get the value of that element
- Here is the format
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
- So if I create the list even_numbers
even_numbers = [2, 4, 6, 8, 10]
- The index of the first element is 0 ...
- and the index of the last is 4
- We can use an index to get the value of each element
>>> even_numbers[0]
2
>>> even_numbers[1]
4
>>> even_numbers[2]
6
>>> even_numbers[3]
8
>>> even_numbers[4]
10
- 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, 2, 3, 4]
- We can change the first number like this
>>> numbers[0] = -1
>>> numbers
[-1, 2, 3, 4]
- We can use indexes in a
for loop ...
- to change every element in a list ...
- by adding 1 to the element
>>> nums = [1, 2, 4, 5]
>>> for index in range(len(nums)):
... nums[index] += 1 # means nums[index] = nums[index] +1
...
>>> nums
[2, 3, 5, 6]
>>>
Using range with Indexes
- If you need to change every element in a list ...
- you need a
for loop where the loop variable ...
- gets every possible index value
- We can create this list of indexes using 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
- If we call range
with the length of the array as its 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(f"nums[{index}] = {nums[index]}")
...
nums[0] = 1
nums[1] = 2
nums[2] = 3
nums[3] = 4
nums[4] = 5
- If we want to change all the numbers in a list by adding 2 ...
- 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] += 2
...
>>> nums
[3, 4, 5, 6, 7]
- Remember that
nums[index] += 1
means
nums[index] = nums[index] + 1
When to Use Indexes
- You could use indexes to loop through a list
>>> l1 = [3,6,9,12]
>>> for index in range(len(l1)):
... print(l1[index])
...
3
6
9
12
- But why bother?
- Looping over the list itself ...
- instead of using indexes is easier ...
- and simpler
>>> for elem in l1:
... print(elem)
...
3
6
9
12
- You should only use indexes ..
- when you want the value of a particlar element
>>> l1[2]
9
- Or when you want to change EVERY element in the list
>>> l1
[3, 6, 9, 12]
>>> for index in range(len(l1)):
... l1[index] = l1[index] * 2
...
>>> l1
[6, 12, 18, 24]
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]
- You need to have two indexes to create a slice
- The first index is the index ...
- of first element we want in the new list
- The second index is trickier
- The second index is not the index of the last element we want
- 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]
- That means the
default value
of the fist index is 0
- 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]
- So the default value of the second index is the length of the list
- 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(value) |
Adds value 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(value) |
Returns the index of the first element whose value is equal to value.
A ValueError exception is raised
if value is not found in the list.
|
| insert(index, value) |
Inserts value into the list at the specified index.
When a value is inserted into a list, the list is expanded in size
to accommodate the new value.
The value that was previously at the specified index,
and all the values 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 values in the list so they appear in ascending order
(from the lowest value to the highest value)
|
| reverse() |
Reverses the order of the values 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
>>> teams
['Red Sox', 'Orioles', 'Blue Jays', 'Rays', 'Yankees']
>>> "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.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]
Fairness
Class Exercise
Class Quiz