Section 10-Lists
Notes on Lists
Necessary Vocabulary
-
Indexing / List Index - The position of an element in a list, starting from 0
-
append
,remove
,pop
- Various methods, append adds an element to the end, remove removes at an index, and pop removes the last item.
-
Elements [in a list] - An item in a list.
-
Nesting - Having one data type or function inside another data type or function, such as lists or loops.
- array - Another name for a list, depends on the language
What are Lists?
- Lists are a collection of data in a sequence that is an iterable
- Each sequence is demarcated with an index, starting from 0. This is known as base 0 indexing
- In memory, it is stored as a variable name with multiple pointers to each variable stored in a certain order
- Lists can also be called arrays
- Lists have methods that act upon the list and change them. This moves the pointers within RAM to change the parts of the list.
A MASSIVE NOTE: Lists methods Mutate, meaning they actively change the list, but they don't return anything. This means that return a None-type, which you cannot manipulate
fruits = ["apple", "banana", "kiwi", "pomegranate"]
print(f"Fruits before append: {fruits}")
fruits.append("dragonfruit") # ADDS TO THE END OF THE LIST
print(f"Fruits after append: {fruits}")
food = ["apple", "banana", "kiwi", "pomegranate"]
vegetables = ["carrot", "cucumber", "eggplant"]
print(f"Fruits before extend: {fruits}")
fruits.extend(vegetables) # adds the vegetable list to the end of the food list
print(f"Fruits after extend: {fruits}")
fruits = ["apple", "banana", "kiwi", "pomegranate"]
print(f"Fruits before insert: {fruits}")
fruits.insert(1, "dragonfruit")
print(f"Fruits after insert: {fruits}")
fruits = ["apple", "banana", "kiwi", "pomegranate"]
print(f"Fruits before pop: {fruits}")
fruits.pop()
print(f"Fruits after pop (no parameter): {fruits}")
fruits.pop(0)
print(f"Fruits after pop (specifying index 0): {fruits}")
fruits = ["apple", "banana", "kiwi", "pomegranate"]
print(f"Fruits before remove: {fruits}")
fruits.remove("apple")
print(f"Fruits after remove (removing apple): {fruits}")
fruits.remove("kiwi")
print(f"Fruits after remove (removing kiwi): {fruits}")
Question 2
In each instance, would we use a list?
We want to represent a sequence of children in order.
We want to represent the number of animals in a zoo.
We want to repeatedly find the derivative of a number.
We want to represent Key value pairs of schools and their quantities
We want to represent the grades of a classroom
Answer!
1. Yes2 No
3. No
4. No
5. Yes
Question 3
{
mgAmounts ← [50, 230, 63, 98, 80, 120, 71, 158, 41]
bestAmounts ← []
mgPerDay ← 360
mgMin ← mgPerDay * 0.3
FOR EACH mgAmount IN mgAmounts
{
IF (mgAmount ≥ mgMin)
{
<MISSING CODE>
}
}
}
What can replace Consider the following code segment What does We can use The two programs below are both intended to display the total number of hours from a list of durations in minutes. Program One: Program Two a. Program 1 displays the correct total number of hours, while Program 2 does not. A javelin thrower is writing code to track the distance of their throws and how far they are from their target distance.
This is what they have so far: A friend points out that they can reduce the complexity of their code by using the abstractions of lists and loops. The programmer decides to "refactor" the code, to rewrite it so that it produces the same output but is structured better. Which of these is the best refactor of the code? The following code snippet processes a list of strings with a loop and conditionals: The code relies on one string procedure, LEN(string), which returns the number of characters in the string. Answer!
Only b, as it is the only item that correctly uses the method and doesn't improperly extend the length.
Question 4
{
sevenWonders ← ["Aurora", "Grand Canyon", "Great Barrier Reef", "Guanabara Bay", "Mount Everest", "Parícutin", "Victoria Falls"]
sevenWonders[4] ← "Komodo"
sevenWonders[6] ← "Table Mountain"
}
sevenWonders
store?Answer!
"Aurora", "Grand Canyon", "Great Barrier Reef", "Komodo", "Mount Everest", "Table Mountain", "Victoria Falls"
TwoDArray = [[1, 0, 1, 0, 1, 0, 0, 0], [0, 0, 0, 0, 1, 0, 1, 1], [1, 1, 0, 0, 0, 1, 1, 1], [0, 0, 0, 0, 1, 1, 1, 1]]
print(TwoDArray[0]) # print first sublist
print(TwoDArray[1]) # print second sublist
print(TwoDArray[2]) # print third sublist
# These 1s and 0s could represent anything. AMAZING DATA ABSTRACTION!
bin_0 = 0
bin_1 = 0
for array in TwoDArray:
for bin in array:
if bin == 0:
bin_0 += 1
elif bin == 1:
bin_1 += 1
print(f"Num 0s: {bin_0}")
print(f"Num 1s: {bin_1}")
Applying Iterationfor
and while
loops to iterate over loops! Then we can manipulate each element in the list for a certain purpose (adding, adding to another list, removing, etc.)
However, recall that each list item is at an index
, and we can't exceed the number of indices that an element has, otherwise we get a IndexError: List out of range
{
totalMins ← 0
durations ← [32, 56, 28, 27]
FOR EACH duration IN durations
{
totalMins ← totalMins + duration
}
totalHours ← totalMins / 60
DISPLAY(totalHours)
}
{
totalMins ← 0
durations ← [32, 56, 28, 27]
FOR EACH duration IN durations
{
totalMins ← totalMins + duration
totalHours ← totalMins / 60
}
DISPLAY(totalHours)
}
b. Program 2 displays the correct total number of hours, while Program 1 does not.
c. Both programs display the correct total number of hours, but Program 1 unnecessarily repeats arithmetic operations.
d. Both programs display the correct total number of hours, but Program 2 unnecessarily repeats arithmetic operations. Answer!
Correct answer: d
{
totalDistance ← 0
targetDistance ← 90
throw1 ← 85.2
DISPLAY(targetDistance - throw1)
totalDistance ← totalDistance + throw1
throw2 ← 82.8
DISPLAY(targetDistance - throw2)
totalDistance ← totalDistance + throw2
throw3 ← 87.3
DISPLAY(targetDistance - throw3)
totalDistance ← totalDistance + throw3
avgDistance ← totalDistance / 3
DISPLAY(avgDistance)
These are all closed so you can see each without being eye-bombed.
a
targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
totalDistance ← 0
FOR EACH throw IN throws
{
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
}
avgDistance ← totalDistance / LENGTH(throws)
DISPLAY(avgDistance)
b
targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
totalDistance ← 0
FOR EACH throw IN throws
{
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
}
avgDistance ← totalDistance / 3
DISPLAY(avgDistance)
c
targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
totalDistance ← 0
FOR EACH throw IN throws
{
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
avgDistance ← totalDistance / LENGTH(throws)
}
DISPLAY(avgDistance)
d
targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
FOR EACH throw IN throws
{
totalDistance ← 0
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
avgDistance ← totalDistance / LENGTH(throws)
}
DISPLAY(avgDistance)
e
targetDistance ← 90
throws ← [85.2, 82.8, 87.3]
FOR EACH throw IN throws
{
totalDistance ← 0
DISPLAY(targetDistance - throw)
totalDistance ← totalDistance + throw
}
avgDistance ← totalDistance / LENGTH(throws)
DISPLAY(avgDistance)
Answer!
Correct answer: a
{
words ← ["cab", "lab", "cable", "cables", "bales", "bale"]
wordScore ← 0
FOR EACH word IN words {
IF (LEN(word) ≥ 5) {
wordScore ← wordScore + 3
} ELSE {
IF (LEN(word) ≥ 4) {
wordScore ← wordScore + 2
} ELSE {
IF (LEN(word) ≥ 3) {
wordScore ← wordScore + 1
}
}
}
}
DISPLAY(wordScore)
}
What value will this program display?
Answer!
Correct answer: 13
arr = [9,1,5,6,3,7,2,8]
print(f"array before sort {arr}")
def insertion_sort(arr):
for index in range(1,len(arr)): # repeats through length of the array
value = arr[index]
i = index - 1
while i >= 0:
if value < arr[i]:
arr[i+1] = arr[i] # shift number in slot i to the right
arr[i] = value # shift value left into slot i
i = i - 1
else:
break
IS = insertion_sort(arr)
print(f"array after sort {arr}")