Chapter 5
- Chapter Sections
- Section 5.1: Lists, Indexes, and List Methods (problems)
- Section 5.2: While Loops and Modifying List Items (problems)
- Section 5.3: For Loops and the in Operator (problems)
- Section 5.4: Lists of Objects (problems)
- Section 5.5: Objects with List Member Variables (problems)
Section 5.1: Lists and List Methods
Introduction
A list is a collection of data types or other objects. A string is much like a list, except that a string can only contain characters, a list can contain anything. Lists can even contain other lists. We use square brackets [ ] to denote a list.
List Examples
num_list = [1, 2, 3] @
str_list = ["abc", "lmn", "xyz"] @
mixed_list = [1, True, "some words"] @
list_of_lists = [num_list, str_list, mixed_list] @
small_list = [1] @
empty_list = [] @
bigger_list = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
- The square brackets [ ] denote a list. Items are separated by a comma.
- Lists can be empty. This may not seem useful, but we can add items to a list later.
- Lists can be very large. A list on an ordinary computer could be on the order of billions of items. Essentially the only limitation is the amount of computer memory (RAM) that is available.
Indices
The word index is the technical term for an integer that is used for referencing an item of a list. In computer science, the first index of a list is always 0, not 1 like you might expect. In practically every programming language, the first index is always 0.
One major advantage of using lists is that fewer variables are needed. Lets say a teacher needs to record all of the grades of the students in a class of 8 students. The teacher could create 8 separate grade variables, one for each of the students. Or, the teacher could create a single list containing all of the grades.
List Examples
grade1 = 82 @
grade2 = 99 @
grade3 = 67 @
grade4 = 87 @
grade5 = 97 @
grade6 = 100 @
grade7 = 43 @
grade8 = 91
OR
grade_list = [82, 99, 67, 87, 97, 100, 43, 91]
Just imagine how tedious it would be to create 80 separate variables if a teacher had 80 students in her classes. One single list can contain 80 items and many more.
We still need to be able to access and possibly change each number however. Suppose a student completes an extra credit assignment and gets 5 more points added to their grade. Lets say the student is the 4th student on the list. We need a way to change the 4th number on the list by adding 5 to it. This is when indices become important. We can use square brackets to access the 4th student's grade using the index of 3. Recall that the first index is 0, so the index for the 4th student is actually 3.
Using An Index To Modify An Item
grade_list[3] += 5
The above code adds 5 to the grade of the student with the index of 3 (the 4th student on the list). So now the resulting list is: [82, 99, 67, 92, 97, 100, 43, 91]
Another Example Of Using Indices To Change Items
num_list = [5, 10, 15, 20, 25] @
num_list[0] = 7 @
num_list[3] = 22 @
num_list[4] = 27
The resulting list is now:
[7, 10, 15, 22, 27]
- For example, when num_list[0] appears in the code, it represents the item at index 0, not the entire list.
- When num_list[0] is modified, only the item in the list is modified, not rest of the list.
List Methods
List methods are functions that are specifically used with a list. Recall, to use a method we need to use the dot operator to access the method. The methods are for the entire list, not the individual items, so brackets are not needed.
Common List Methods
| Method | Description |
| .append(x) | Adds the item x at the end of the list. |
| .insert(n,x) | The item x is inserted at index n. The item already at index n moves down the list, but stays inside of the list. |
| .remove(x) | Searches through the list and removes the first item equal to x. |
| .reverse() | Reverses the order of all of the items. |
`
The Append Method
num_list = [1, 2, 3] @
num_list.append(4)
The resulting list is now:
~[1, 2, 3, 4]
The Reverse Method
color_list = ["blue", "green", "yellow", "red"] @
color_list.reverse()
The resulting list is now:
~["red", "yellow", "green", "blue"]
The Remove Method
num_list = [1, 2, 3, 1, 2, 3] @
num_list.remove(2)
The resulting list is now:
~[1, 3, 1, 2, 3]
The Insert Method
num_list = [1, 2, 3, 4] @
num_list.insert(1,5)
The resulting list is now:
~[1, 5, 2, 3, 4]
num_list.insert(3,6)
The resulting list is now:
~[1, 5, 2, 6, 3, 4]
The .insert(n,x) method inserts the item at the index given by n. All of the items that appear afterwards are pushed down the list.
Section 5.1 Name:____________________
Lists and List Methods
Score:      /5
Problems
- Determine what the list will be equal to after each line of code executes.
num_list = [8, 6, 4, 2]
num_list[1] = 3
|
num_list = [20, 30, 40, 10]
num_list[0] += 7
|
num_list = [5, 10, 15, 20]
num_list[2] = num_list[1]
|
num_list = [8, 5, 7, 2]
num_list[3] = num_list[1] + 3
|
- Determine what the list will be equal to after each line of code executes.
num_list = [10, 20, 30, 40]
num_list.append(17)
|
num_list = [12, 13, 91, 22]
num_list.reverse()
|
str_list = ["abc", "abd", "ab", "a"]
str_list.remove("ab")
|
num_list = [6, 1, 3, 4]
num_list.append(2)
num_list.reverse()
|
- Determine what the list will be equal to after each line of code executes.
num_list = [5, 3, 1, 7]
num_list.insert(0,6)
|
num_list = [17, 31, 45, 22]
num_list.insert(2,15)
|
str_list = ["abc", "wxyz"]
str_list.insert(1,"mnopq")
|
num_list = [8, 5, 7, 2]
num_list.insert(1, 6)
num_list.insert(3, 9)
|
- Determine what the list will be equal to after each line of code executes.
Code
num_list = [1, 2, 3, 4] @
num_list[1] = 5 @
num_list.append(6) @
num_list.reverse() @
num_list.insert(1,7)
- Determine what the list will be equal to after each line of code executes.
Code
num_list = [20, 15, 10, 5] @
num_list.insert(0,50) @
num_list.reverse() @
num_list.append(80) @
num_list[3] += 10
Section 5.2: Iterating With While Loops
Introduction
Often it is necessary to modify all of the items in a list systematically, one after the other. This is usually done with a loop. In this section we will be using while loops with indices to iterate through an entire list.
Suppose every student in the class gets an extra 5 points added to their grade. Even with a large list this can be done with just a handful of lines of code. Let grade_list = [80, 82, 93, 72, 84, 62, 12, 90, 86, 0]. Note that this list has 10 items.
Loop Through The List
i=0 @
while i<10: @
~grade_list[i] += 5 @
~ i += 1
The resulting list is now:
~[85, 87, 98, 77, 89, 67, 17, 95, 91, 5]
The len Function
Python has a very convenient function for determining the size, or length, of a list. The len function is short for length. If you are ever unsure of how long a list is, which is actually very common, simply pass the list to the len function and it will return the size of the list as an integer.
The len Function
name_list = ["Bob", "Jack", "Mary", "Sammy", "Joe"] @
list_length = len(name_list)
list_length will be equal to 5.
The len function is convenient to use with while loops, especially when we are unsure of the size of the list when writing the code. The example below is similar to the first example, except this loop uses the len function.
Using len
i=0 @
while i < len(grade_list): @
~grade_list[i] += 5 @
~i += 1
With this code we do not need to know how many grades are in the list when we write the code. There could be 10 students, 80 students, or 10,000 students. This code will work to add 5 to each grade regardless of how many grades there are.
Finding the Average of The Numbers in a List
One practical application of iterating through a list is to find the average of all of the numbers in a list. Recall that the average is the total of all of the numbers being averaged divided by how many numbers there are. Suppose the list of numbers is called num_list. Then the following code will find the average of num_list even if we do not know the size of num_list when we write the code.
Finding the Average of num_list
total = 0 @
i=0 @
while i < len(num_list): @
~total += num_list[i] @
~i += 1 @
average = total / len(num_list)
Notice that len is used in two places in the code. Like before, len is used as part of the while loop. It is also used after the total has been calculated to find the average.
More Examples
The example below combines two lists, one for first names and one for last names. The initial lists are: first_names = ["Mary", "Fred", "Jack"] and last_names = ["Smith", "Hitchcock", "Zhang"]
Finding the Average of num_list
full_names = [] @
i=0 @
while i < len(first_names): @
~full_names.append(first_names[i] + " " + last_names[i]) @
~i += 1
After the code above executes, full_names will be:
["Mary Smith", "Fred Hitchcock", "Jack Zhang"]
The next example doubles every second number. The initial list is num_list = [11, 13, 15, 17, 19, 21].
Double Every Second Number
i=1 @
while i < len(num_list): @
~num_list[i] *= 2 @
~i += 2
After the code above executes, num_list will be:
[11, 26, 15, 34, 19, 42]
The example below finds the maximum value of numbers in the list. The initial list is num_list = [56, 32, 12, 99, 76, 16, 7]. It is assumed in the code that all the numbers are positive.
Find the Maximum
m=0 @
i=0 @
while i < len(num_list): @
~if m < num_list[i]: @
~~m = num_list[i] @
~i += 1
After the code above executes, m will be 99.
Section 5.2 Name:____________________
Iterating With While Loops
Score:      /5
Problems
- Assume that number_list = [1, 3, 5, 7, 9, 11, 13, 15].
- What is returned by len(number_list)?
- What will number_list be equal to after the following for-loop?
i = 0 @
while i < len(number_list): @
~number_list[i] += 10 @
~i += 1
- Assume that number_list = [16, 8, 4, 2, 1].
- What is returned by len(number_list)?
- What will number_list be equal to after the following for-loop?
i = 0 @
while i < len(number_list): @
~number_list[i] *= 2 @
~i += 1
- For the list: number_list = [10, 20, 30, 40, 50] write code for a while loop that will add 100 to each?
~~~~~~~~~~~
@@@@@@
- For the list: number_list = [60, 50, 40, 30, 20, 10] write code for a while loop that will subtract 2 from each?
~~~~~~~~~~~
@@@@@@
- For the list: number_list = [60, 50, 40, 30, 20, 10] write code for a while loop that will add 5 to items with an even index? What will number_list be equal to afterwards.
~~~~~~~~~~~
@@@@@@
- For the list: verb_list = ["talk", "walk", "sing"] write code for a while loop that will add "ing" to each verb.
~~~~~~~~~~~
@@@@@@
- Based on example 15, write code for a while loop that will find the minimum number in a list of numbers. Assume the list is called num_list and that no number is greater than 100.
~~~~~~~~~~~
@@@@@@@@@@@@@@@@
Section 5.3: For Loops and the in Operator
Like a while-loop, for-loops execute a block of code for multiple iterations. However, in Python, for-loops are primarily used to iterate through the items of a list. One advantage of using for-loops is that it can be easier to use a for loop than a while-loop to iterate through the items in a list. But, the items cannot be changed with a for-loop.
For-Loop Example
num_list = [5, 10, 15, 20, 25] @
for num in num_list: @
~print(num)
Screen:
5 @
10 @
15 @
20 @
25
- In addition to the keyword for, the word in is also a keyword. More on this keyword later in the lesson.
- The variable num that shows up in the for-loop is a variable that is temporarily set equal to each item in the loop, one after another.
- The loop executes an iteration for each item in the list. The variable in the for-loop (num in this example) is equal to a different item each iteration.
Another For-Loop Example
str_list = ["one", "two", "three", "four"] @
for word in str_list: @
~print(word)
Screen:
one @
two @
three @
four
One advantage of using for-loops is that the code is simpler to write and sometimes simpler to understand. Consider the two examples below, one example that uses a while-loop to find the sum of a list of numbers and another example that uses a for-loop.
Using A While-Loop
num_list = [5, 10, 15, 20, 25] @
sum_of_list = 0 @
i = 0 @
while i < len(num_list): @
~sum_of_list += num_list[i] @
~i += 1
Using A For-Loop
num_list = [5, 10, 15, 20, 25] @
sum_of_list = 0 @
for num in num_list: @
~sum_of_list += num
The while-loop example requires use of the index i. However, the for-loop does not require the use of an index, which simplifies the code. However, behind the scenes, Python still uses indexes or other iterating methods to execute loops such as a for-loop. The code has been simplified for what the programmer needs to write.
The major draw back to using for-loops is that it is not possible to modify the items of the list, its only possible to use the items. This is because a copy is made to the variable contained in a for-loop. For example:
Does Nothing
num_list = [1, 2, 3, 4, 5, 6] @
for num in num_list: @
~num = 20
In this example it looks as though all of the items in the list should be set equal to 20. However, this loop actually does nothing at all to the list. The variable num is not actually a list item, but is instead set equal to the same value as a list item during each iteration of the loop. Setting num equal to 20 only changes num during that iteration, not the list item.
Strings Are Lists of Characters
Recall that letters, punctuation marks, characters in other writing systems, and symbols generally are represented by Unicode and are all called characters. It was mentioned before that strings are essentially lists of characters. The only difference is that strings are only allowed to contain characters and are optimized to work with only characters. Otherwise, they are the same. We can use for-loops with strings just as we did with lists.
Iterating Through Letters
for letter in "Hello": @
~print(letter)
Screen:
H @
e @
l @
l @
o
The in Keyword
The keyword in can be used as part of the syntax a for-loop, but it can also be used to test if an item is contained in a list. Like the operator ==, the keyword in returns a True or False value (bool).
Common List Methods
| Code | Return Value |
| 12 in [0, 3, 6, 9, 12, 15] | True |
| 8 in [0, 3, 6, 9, 12, 15] | False |
| "F" in "fish" | False |
| "H" in "Hello" | True |
| "six" in ["one", "two", "three", "four"] | False |
Section 5.3 Name:____________________
For Loops and the in Operator
Score:      /5
Problems
- What will print to the screen? What is num equal to in the first iteration of the for-loop? What is it equal to in the last iteration?
num_list = [12, 32, 17, 22, 12] @
for num in num_list: @
~print(num)
Screen:
- What will print to the screen?
for letter in "John Smith": @
~print(letter)
Screen:
- Write code to find the sum of numbers = [32, 54, 23, 55, 101, 51, 78]?
~~~~~~~~~
@@@@@@@@@
- What will the list nl = [40, 20, 30, 50] be equal to after the following loop executes?
for n in nl: @
~n += 5
Screen:
- Will the following evaluating to True or False? Assume that num_list = [2, 3, 5, 7, 11, 13], color_list = ["red", "green", "blue", "yellow"] and sentence = "You're wrong".
| Code | Return Value |
| 5 in num_list | |
| 17 in num_list | |
| "cyan" in color_list | |
| "yellow" in color_list | |
| "e" in sentence | |
| " " in sentence | |
Section 5.4: Lists of Objects
Introduction
So far, primarily we have seen lists that contain numbers with a few examples of lists that contain strings. However, as was mentioned in 5.1, lists can contain all sorts of different items, including other lists. Lists can also contain objects of other classes.
Lists Containing Custom Objects
A List of a 100 Students
class Student: @@
~def __init__(self, name, major): @
~~self.name = name @
~~self.major = major
The code below fills a list with 100 students:
student_list = [] @
s = 0 @
while s < 100: @
~stu = Student("Jack", "Biology") @
~student_list.append(stu) @
~s += 1
Notice that ALL of the students in this example are named Jack and study Biology. Although the list in the example above will contain one hundred students, the drawback of this approach is the specific information on each of the students has to be entered separately. Typically, a programmer will need to write code to ask the user for specific information on each of the students to be entered separately, again using while or for loops, or open a file with this information.
The function below is an alternative to the first example. It asks the user for data on a number of students. This is a potentially much more useful way to generate a list of students.
Student List Generating Function
def get_student_list(): @
~student_list = [] @
~count = int(raw_input("Enter the number of students:")) @
~s = 0 @
~while s < count: @
~~name = raw_input("Name:") @
~~major = raw_input("Major:") @
~~stu = Student(name, major) @
~~student_list.append(stu) @
~~print("\n") @
~~s += 1 @
~return(student_list)
The Dot Operator and Lists
In order to access the various member variables of each item in the list, we can use the dot operator in combination with []. The example below changes the major of the first 30 students created in example 20.
Changing the Major of the First 10 Students
i = 0 @
while i < 10: @
~student_list[i].major = "Computer Science" @
~i += 1
Changing the Major of the Next 20 Students
i = 10 @
while i < 30: @
~student_list[i].major = "Literature" @
~i += 1
Lists Containing Other Lists
It is possible with Python to put even other lists inside of lists. If each sublist is the same size, then the list of lists is actually a table or matrix.
A List of Lists
L = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ]
Equivalent Table:
1 ~ 2 ~ 3 @
4 ~ 5 ~ 6 @
7 ~ 8 ~ 9
However, the sublists do not all need to be the same size. The code below uses two nested while loops to create a triangular shaped table.
A List with Different Sizes for Sublists
list_of_lists = [] @
n = 1 @
while n <= 6: @
~sub_list = [] @
~k=0 @
~while k <= n: @
~~sub_list.append(k) @
~~k += 1 @
~list_of_lists.append(sub_list) @
~n += 1
Equivalent Table:
1 @
1 ~ 2 @
1 ~ 2 ~ 3 @
1 ~ 2 ~ 3 ~ 4 @
1 ~ 2 ~ 3 ~ 4 ~ 5 @
1 ~ 2 ~ 3 ~ 4 ~ 5 ~ 6
For each iteration of the outer while, a separate sublist (a row of the table) is created. The inner while loop fills each sublist.
We can modify some of the lists in the list of lists by appending the number 20 to each of the sublists. Again we can use the dot operator in combination with [], but this time for a method.
Appending 20 to Each Sublist
i = 0 @
while i < len(list_of_lists): @
~list_of_lists[i].append(20) @
~i += 1
Equivalent Table:
1 ~ 20 @
1 ~ 2 ~ 20 @
1 ~ 2 ~ 3 ~ 20 @
1 ~ 2 ~ 3 ~ 4 ~ 20 @
1 ~ 2 ~ 3 ~ 4 ~ 5 ~ 20 @
1 ~ 2 ~ 3 ~ 4 ~ 5 ~ 6 ~ 20
Section 5.4 Name:____________________
Lists of Objects
Score:      /5
Problems
- Answer the following questions based on the code below?
class Pet: @@
~def __init__(self, name, species): @
~~self.name = name @
~~self.species = species
The code below fills a list with many pet objects:
pet_list = [] @
p = 0 @
while p<1000: @
~pet = Pet("Mittens", "Cat") @
~pet_list.append(pet) @
~p += 1
- How many pet objects are created?
- Write code to set the species of all of the pets to be "Dog"?
~~~~~~~~~
@@@@@@@@@
- Write code that will set the name of the first 100 pet objects to be "Fido"?
~~~~~~~~~
@@@@@@@@@
- Write code that will set the name of the last 100 pet objects to be "Rex"?
~~~~~~~~~
@@@@@@@@@
- Answer the following questions based on the code below?
class City: @@
~def __init__( self, name, pop_size ): @
~~self.name = name @
~~self.pop_size = pop_size
The code below fills a list with many city objects (population size measured in thousands):
city_list = [] @
c = 0 @
while c < 500: @
~city = City( "Atlanta", 400 ) @
~city_list.append(city) @
~c += 1
- How many city objects are created?
- Write code to set the name of all of the city objects to be "NYC"?
~~~~~~~~~
@@@@@@@@@
- Write code that will set the population size of the first 50 cities to be 600 thousand. <
~~~~~~~~~
@@@@@@@@@
- Write code that will set the population size of the last 50 cities to be 200 thousand.
~~~~~~~~~
@@@@@@@@@
Section 5.5: Objects with List Member Variables
Introduction
In the last section we saw lists that contained objects of classes. In this section we are going to see objects that contain lists as member variables. Suppose for example that you wish to create a CarDealership class. Suppose you also want each CarDealership object to contain a list of Car objects of a Car class that represents the cars that the dealership has it is trying to sell. Well, the CarDealership class could simply have a list as a member variable for storing the cars it has to sell.
Car and CarDealership Classes
class Car: @@
~def __init__(self, make, model, year): @
~~self.make = make @
~~self.model = model @
~~self.year = year @@@
class CarDealership: @@
~def __init__(self, name): @
~~self.name = name @
~~self.carsForSale = [] @@
~def addCarToSell(self, car): @
~~self.carsForSale.append(car) @@
~def printCars(self): @
~~for car in self.carsForSale: @
~~~print(car.make+" "+car.model+" "+str(car.year))
In the above example, the list contained inside the CarDealership class is initialized to be an empty list. It may seem strange that the list is initially empty, but the class also has a method for adding cars to the list. In this way, we can create the CarDealership objects first, then add the Car objects later. Alternatively, we could have designed the CarDealership class so that we would pass a pre-made list to the __init__ method of CarDealership, but we would have to know what cars we wanted to add before we even made the CarDealership object.
Using the Car and CarDealership Classes
dealership = CarDealership("Mike's Cars") @@
c1 = Car("Ford", "Mustang", 2017) @
dealership.addCarToSell(c1) @@
c2 = Car("Ford", "Focus", 2015) @
dealership.addCarToSell(c2) @@
c3 = Car("Chevrolet", "Cobalt", 2016) @
dealership.addCarToSell(c3) @@
dealership.printCars()
Screen
Ford Mustang 2017 @
Ford Focus 2015 @
Chevrolet Cobalt 2016
Section 5.5 Name:____________________
Objects with List Member Variables
Score:      /5
Problems
- Make your own objects of the classes created in example 29
- Write code to create a CarDealership object with whatever name you want and 3 separate Car objects that the dealership sells. Make sure to add them to the CarDealership object.
Your Code:
~~~~~~~~~
@@@@@@@@@@@@@@@
- What will print to the screen if you execute the method .printCars() with your CarDealership object.
Screen:
~~~~~~~~~
@@@@@@@
- Create your own classes like example 29.
- Write code for a class that will be contained in a second class, like Car. This class should have an init method and at least two member variables.
- Write code for a class that contains objects of the first class in a list, like CarDealership. The list should be a member variable. Make sure this class also has one other member variable, like a number or a string.
- Write code for a method of the second class that will add objects of the first class to the second.
- Write code for some example objects. One object of the second class and three objects of the first class added to the object of the second class.
Class Code:
~~~~~~~~~
@@@@@@@@@@@@@@@@
Object Code:
~~~~~~~~~
@@@@@@@@@