Upload
others
View
4
Download
0
Embed Size (px)
Citation preview
9/11/19
1
Lecture 7Arrays and Lists
What are we going to cover today?
• Storing arrays of data (lists)
• Operations on lists
Imagine you want to read in the grades of five quizzesgrade_1 = int(input("Enter grade: "))grade_2 = int(input("Enter grade: "))grade_3 = int(input("Enter grade: "))grade_4 = int(input("Enter grade: "))grade_5 = int(input("Enter grade: "))
• Notice: we need five different variables to store all five values.• Now, if we want to find the average:
average = (grade_1 + grade_2 + grade_3 + grade_4 + grade_5) / 5
Similar data
• When we have several data values of the same type, storing them in separate variables doesn’t make much sense• We’d like to find a way to group all those similar data values together
in one container.• The way this is done is with a list• This is often called an array, but in Python, we refer to this as a list.
An array in memory
• Just like we can think of a variable as a single “box” of memory, an array, or list, can be thought of as a collection of boxes:
Single variableList/Array
…
Naming lists
• A list acts like another “type” of variable• We assign a single name to
the entire list as a whole
GradeList
…
9/11/19
2
Naming lists
• A list acts like another “type” of variable• We assign a single name to
the entire list as a whole• The individual elements of a
list are numbered, starting at 0
GradeList
…
1
0
2
3
n
Naming lists
• A list acts like another “type” of variable• We assign a single name to the
entire list as a whole• The individual elements of a
list are numbered, starting at 0• Each of the individual
elements can contain a value
GradeList
…
1
0
2
3
n
8
11
4
7
15
Referring to elements
• To get a specific element, we will write:
<List name>[<element number>]
• For example, GradeList[2]• The list name is GradeList• We want element 2 (the third
element)• When speaking, it’s common to
say “sub” as in “subscript”• “GradeList sub 2”
GradeList
…
1
0
2
3
n
8
11
4
7
15GradeList[2]
Referring to elements
•We can refer to elements in a program like we would a variable:
GradeList[2] = GradeList[0]+GradeList[1]
GradeList
…
1
0
2
3
n
8
11
4
23
15
Referring to elements
• The element number can be a variable.
i = 2GradeList[i] = 1
GradeList
…
1
0
2
3
n
8
11
4
1
15
Creating a List
• To create a list variable, we assign a list to the variable name• Lists are denoted by brackets, with comma-separated values inside.
grades = [87, 93, 75, 100, 82, 91, 85]names = ['George', 'John', 'Thomas']
9/11/19
3
What will the following output?
grades = [87, 93, 75, 100, 82, 91, 85]grades[1] = 10grades[2] -= 90grades[3] = grades[1]+grades[2]print(grades[3])
What will the following output?
grades = [87, 93, 75, 100, 82, 91, 85]grades[1] = 10grades[2] -= 90grades[3] = grades[1]+grades[2]print(grades[3])Console
Next
What will the following output?
grades = [87, 93, 75, 100, 82, 91, 85]grades[1] = 10grades[2] -= 90grades[3] = grades[1]+grades[2]print(grades[3])Console
Next
grades
0 87
1 93
2 75
3 100
4 82
5 91
6 85
What will the following output?
grades = [87, 93, 75, 100, 82, 91, 85]grades[1] = 10grades[2] -= 90grades[3] = grades[1]+grades[2]print(grades[3])Console
Next grades
0 87
1 10
2 75
3 100
4 82
5 91
6 85
What will the following output?
grades = [87, 93, 75, 100, 82, 91, 85]grades[1] = 10grades[2] -= 90grades[3] = grades[1]+grades[2]print(grades[3])Console
Next
grades
0 87
1 10
2 -15
3 100
4 82
5 91
6 85
What will the following output?
grades = [87, 93, 75, 100, 82, 91, 85]grades[1] = 10grades[2] -= 90grades[3] = grades[1]+grades[2]print(grades[3])Console
Next
grades
0 87
1 10
2 -15
3 -5
4 82
5 91
6 85
9/11/19
4
What will the following output?
grades = [87, 93, 75, 100, 82, 91, 85]grades[1] = 10grades[2] -= 90grades[3] = grades[1]+grades[2]print(grades[3])Console-5
Next
grades
0 87
1 10
2 -15
3 -5
4 82
5 91
6 85
Printing a list
• Printing a list will display the list with square brackets, with the values of the elements separated by commas.
grades = [87, 93, 75, 100, 82, 91, 85]print(grades)
Console[87, 93, 75, 100, 82, 91, 85]
Finding the length of a list
• To find the length of a list, we can use the len operation.• len(x) returns the number of elements in list x
grades = [87, 93, 75, 100, 82, 91, 85]print(len(grades))
This will print out 7
Looping through an array
• One of the most common things we’ll do to access all elements of an array is to loop through it. • Say we want the average grade:
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in range(7):
sum += grades[i]average = sum/7print(average)
Looping through an array
• One of the most common things we’ll do to access all elements of an array is to loop through it. • Say we want the average grade:
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in range(7):
sum += grades[i]average = sum/7print(average)
We initialize the sum to 0
Looping through an array
• One of the most common things we’ll do to access all elements of an array is to loop through it. • Say we want the average grade:
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in range(7):
sum += grades[i]average = sum/7print(average)
We’ll loop through all 7 grades
9/11/19
5
Looping through an array
• One of the most common things we’ll do to access all elements of an array is to loop through it. • Say we want the average grade:
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in range(7):
sum += grades[i]average = sum/7print(average)
In each iteration, we’ll increase the sum
Looping through an array
• One of the most common things we’ll do to access all elements of an array is to loop through it. • Say we want the average grade:
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in range(7):
sum += grades[i]average = sum/7print(average)
And finally compute the average
When the size of the list is not known in advance• Often, when writing code, we don’t know how large the list will be• Maybe we just read in grades from a user until the user stopped.
• So, loop using len(list)grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in range(len(grades)):
sum += grades[i]average = sum/len(grades)print(average)
A different type of for loop
• We can write a for loop a different way:for i in <list>:
#do something here
• This will go through all the items in the list, but i will have the value of the element itself (not the element number) when inside the loop.
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in grades:
sum += iaverage = sum/len(grades)print(average)
grades
0 87
1 93
2 75
3 100
4 82
5 91
6 85
sum
0
Next
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in grades:
sum += iaverage = sum/len(grades)print(average)
grades
0 87
1 93
2 75
3 100
4 82
5 91
6 85
sum
0
Next
i
87
i takes the value of the first element, 87
9/11/19
6
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in grades:
sum += iaverage = sum/len(grades)print(average)
grades
0 87
1 93
2 75
3 100
4 82
5 91
6 85
sum
87
Next
i
87
sum was increased by i
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in grades:
sum += iaverage = sum/len(grades)print(average)
grades
0 87
1 93
2 75
3 100
4 82
5 91
6 85
sum
87
Next
i
93
Now i has the value of the second element, 93
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in grades:
sum += iaverage = sum/len(grades)print(average)
grades
0 87
1 93
2 75
3 100
4 82
5 91
6 85
sum
180
Next
i
93
sum is again increased by i
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in grades:
sum += iaverage = sum/len(grades)print(average)
grades
0 87
1 93
2 75
3 100
4 82
5 91
6 85
sum
180
Next
i
75
Now i has the value of the third element, 75
grades = [87, 93, 75, 100, 82, 91, 85]sum = 0for i in grades:
sum += iaverage = sum/len(grades)print(average)
grades
0 87
1 93
2 75
3 100
4 82
5 91
6 85
sum
255
Next
i
75
sum is again increased by i
etc…
Changing a list in a loop
• The second type of for loop does not let us change values in a list:grades = [87, 93, 75, 100, 82, 91, 85]for i in grades:
i = 0• This does not change any of the values in the list grades• Each iteration, i is a separate variable that gets the value from grades
• It is a separate location in memory• Then, i gets assigned 0. But, the memory storing the values of the list does
not change.
9/11/19
7
Changing a list in a loop
• To change values in the list, we need to access the elements directly:grades = [87, 93, 75, 100, 82, 91, 85]for i in range(len(grades)):
grades[i] = 0• This changes all the elements of grades to 0
range(x) is a list
• When we have been writing a for loop with range, we’ve essentially been using a list!• range(x) is just a way to generate a list of all elements from 0 to x-1• So, the following are equivalent:
for i in range(10):print(i)
for i in [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]:print(i)
• (Actually, range is a little different than a list – you can’t change an range, the way we’ll talk about changing lists, next)
List operations: adding another element
• We often want to add an element to a list• For example, we read information from a user and for each new
entry, we add it to the end of the existing list.• This is done using the append command.• The format is different from things we’ve seen to this point!
<list name>.append(<thing to add>)
List operations: adding another element
• We often want to add an element to a list• For example, we read information from a user and for each new
entry, we add it to the end of the existing list.• This is done using the append command.• The format is different from things we’ve seen to this point!
<list name>.append(<thing to add>)
Start with the name of the list
List operations: adding another element
• We often want to add an element to a list• For example, we read information from a user and for each new
entry, we add it to the end of the existing list.• This is done using the append command.• The format is different from things we’ve seen to this point!
<list name>.append(<thing to add>)
Then, there is a period and the word append
List operations: adding another element
• We often want to add an element to a list• For example, we read information from a user and for each new
entry, we add it to the end of the existing list.• This is done using the append command.• The format is different from things we’ve seen to this point!
<list name>.append(<thing to add>)
Then, inside of parentheses is the thing you want to add to the list
9/11/19
8
Example: adding a new grade
grades = [87, 93, 75, 100, 82, 91, 85]grades.append(80)print(grades)print(len(grades))
Console[87, 93, 75, 100, 82, 91, 85, 80]8
List operations: addition
• We can add lists together:list1 = [1, 2, 3]list2 = [4, 5, 6]list3 = list1+list2print(list3)
Console[1, 2, 3, 4, 5, 6]
list3
0 1
1 2
2 3
3 4
4 5
5 6
list1
0 1
1 2
2 3
list2
0 4
1 5
2 6
Notice that list 3 is a new list, in different memory locations than list1 and list2
Adding lists instead of appending
• We can add lists as an alternative to using .append()• But, we need to add lists, we can’t just add the element:
grades = [87, 93, 75, 100, 82, 91, 85]grades += [80]j = 95grades += [j]print(grades)print(len(grades))
Console[87, 93, 75, 100, 82, 91, 85, 80, 95]9
Notice that we had to convert the value 80, or the value in the variable j, to a list, by adding [], before we could add it
Indexing into a list
• The use of the [x] for accessing an element of a list is called indexing• The value of x is the index
• Python provides some different ways of indexing, and we’ll see these by illustrating
Example 1: What would the following print?
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[0], grades[6])
Console
Example 1: What would the following print?
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[0], grades[6])
Console87 85
9/11/19
9
Example 2: What would the following print?
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[7])
Console
Example 2: What would the following print?
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[7])
ConsoleIndexError: list index out of range
Trying to access a list element that is past the final element will give an error
Example 3: What would the following print?
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[-1])
Console
Example 3: What would the following print?
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[-1])
Console85
Using negative values goes backward in the list!
Example 4: What would the following print?
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[-7])print(grades[-8])
Console
Example 4: What would the following print?
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[-7])print(grades[-8])
Console87IndexError: list index out of range
Notice that if the length is n, we can index from -n to n-1
We can go out of range backward, also
9/11/19
10
List slicing
• One nice feature in Python is the ability to “slice” a list• This means to take a list and pull out a subpart of the list
• Slicing has the form:<list name>[a:b]
• a indicates the element to start with in the list• b indicates the element to stop before in the list
List slicing examples
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[0:3])print(grades[4:5])print(grades[-3:-1])
Console[87, 93, 75][82][82, 91]
More list slicing
• If you leave off the starting value (a), it means “start at the beginning”• If you leave off the ending value (b), it means “go to the end”
More List slicing examples
grades = [87, 93, 75, 100, 82, 91, 85]print(grades[:3])print(grades[4:])print(grades[:])
Console[87, 93, 75][82, 91, 85][87, 93, 75, 100, 82, 91, 85]
More List slicing examples
• Slicing does not give out-of-range errors• If you try to go past the beginning/end of a list when slicing, you just get the
beginning/end of the list.grades = [87, 93, 75, 100, 82, 91, 85]print(grades[4:300])print(grades[-100:-3])
Console[82, 91, 85][87, 93, 75, 100]
List slicing operations
• List slicing does not make a copy of the sublist until it is assigned somewhere.• So, you can actually change/add to a list by reassigning to a sliced
region.• This is easiest to see by example
9/11/19
11
List adjusting (1)
grades = [87, 93, 75, 100, 82, 91, 85]sublist = grades[1:4]print(grades)print(sublist)
Console[87, 93, 75, 100, 82, 91, 85][93, 75, 100]
List adjusting (2)
grades = [87, 93, 75, 100, 82, 91, 85]sublist = grades[1:4]sublist = []print(grades)print(sublist)
Console[87, 93, 75, 100, 82, 91, 85][]
sublist is a copy of part of the grades list, so adjusting sublist did not affect grades
List adjusting (3)
grades = [87, 93, 75, 100, 82, 91, 85]sublist = grades[1:4]grades[1:4] = []print(grades)print(sublist)
Console[87, 82, 91, 85][93, 75, 100]
We took the part of grades from element 1 through element 3, and replaced it by an empty list!
sublist is, of course, unaffected
List adjusting (4)
grades = [87, 93, 75, 100, 82, 91, 85]sublist = grades[1:4]grades[5:5] = [65, 50]print(grades)print(sublist)
Console[87, 93, 75, 100, 82, 65, 50, 91, 85][93, 75, 100]
We can also add values to the list.
Notice that [5:5] refers to the location just before element 5.
Strings as lists
• Strings are essentially lists of characters!• There are actually some key differences, though…
• We can slice strings just like we slice lists• But, we can’t assign to a sliced region
name = "Texas A&M University"print(name[6:9])name[6:9] = []
ConsoleA&MTypeError: 'str' object does not support item assignment
Exercise
• If we have a string named city_name, how would we get the first 4 and last 4 characters of the city name?
9/11/19
12
Exercise
• If we have a string named city_name, how would we get the first 4 and last 4 characters of the city name?
• city_name[:4] • city_name[-4:]
Exercise
• If we have a string named city_name, how would we get the first 4 and last 4 characters of the city name?
• city_name[:4] • city_name[-4:]
• But, what if the name was only 3 characters long?
Exercise
• If we have a string named city_name, how would we get the first 4 and last 4 characters of the city name?
• city_name[:4] • city_name[-4:]
• But, what if the name was only 3 characters long?• Try it out…city_name = "Arp"print(city_name[:4])print(city_name[-4:])
Exercise
• If we have a string named city_name, how would we get the first 4 and last 4 characters of the city name?
• city_name[:4] • city_name[-4:]
• But, what if the name was only 3 characters long?• Try it out…city_name = "Arp"print(city_name[:4])print(city_name[-4:])
ConsoleArpArp
Remember, when slicing lists, we don’t get out of range errors!
Lists of lists
• We can make lists of listsgrid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]print(grid[0][0])print(grid[1][2])
Console
Next
Lists of lists
• We can make lists of listsgrid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]print(grid[0][0])print(grid[1][2])
Console1
grid[0] is the list [1, 2, 3]So, element [0] of grid[0] is 1
Next
9/11/19
13
Lists of lists
• We can make lists of listsgrid = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]print(grid[0][0])print(grid[1][2])
Console16
grid[1] is the list [4, 5, 6]So, element [2] of grid[1] is 6
Next
Some last notes on lists
• It is a good idea, but not required in Python, for lists to contain elements of the same type• That lets you loop through the list, doing the same operation to each element
• Keep in mind that adding lists puts one list on the end of the other• In other words, lists are not the same as vectors in the mathematics sense
• There are more things you can do with slicing and list operations than just these, but these are the most important.
A Brief Introduction to Dictionaries
• Dictionaries are a different container from lists, but share some similarities• Dictionaries associate key-value pairs• For a given key, there is a single value• Multiple keys could have the same value
• In a “real” dictionary, the “key” is the word• The “value” is the definition• Or the pronunciation• Or the synonyms, etc.
Dictionary
• First, create a dictionary• Assign using { }
• An empty dictionary is just {}, • e.g.: age = { }
• Any initial elements can be described as <key>:<value>, separated by commas, in the {}• e.g: age = {'John' : 21, 'James' : 25}
Dictionary Elements
• Access a dictionary element using []• The value in the [] is the key• The key does not have to be an integer!
• Example:age['John'] = 23age['Jill'] = 21age['James'] = 20age['Jessica'] = 23
Operations on Dictionaries and Lists
• Can loop through a dictionary using for..in (similar to a list)for <iterator> in <dictionary/list>:
#Iterator takes on the value of the KEY in a# dictionary, or a value in a list
• Can use in command to test whether an element is in a list, or notif <item> in <dictionary/list>:
#True if the item is a key in the dictionary, or# a value in the list
9/11/19
14
Exampleage = {'John' : 21, 'Jill' : 21}age['James'] = 20age['Jessica'] = 23print(age)for i in age :
print("key", i, ", value",age[i])if 'James' in age:
print("Yes for James")else:
print("No for James")if 'Joe' in age:
print("Yes for Joe")else:
print("No for Joe")
Output
Dictionary Exampleage = {'John' : 21, 'Jill' : 21}age['James'] = 20age['Jessica'] = 23
print(age)
for i in age :print("key", i, ", value",age[i])
if 'James' in age:print("Yes for James")
else:print("No for James")
if 'Joe' in age:print("Yes for Joe")
else:print("No for Joe")
Output{'John': 21, 'Jill': 21, 'James': 20, 'Jessica': 23}key John , value 21key Jill , value 21key James , value 20key Jessica , value 23Yes for JamesNo for Joe