Overview and Notes: 3.10 - Lists

  • Make sure you complete the challenge in the challenges section while we present the lesson!

Add your OWN Notes for 3.10 here:

  • lists help organize and collect data in a program
  • we can locate them through indexing
  • we can add, remove, or change the location of a certain item in the list
  • ITERATIONS: repetition of a function
  • most commonly done through loops (for, while, if...)
  • Analogy: iterations and loops --> bread and butter

Fill out the empty boxes:

Pseudocode Operation Python Syntax Description
aList[i] aList[i] Accesses the element of aList at index i
x ← aList[i] x = aList[i] Assigns the element of aList at index i
to a variable 'x'
aList[i] <- x aList(i) = x Assigns the value of a variable 'x' to
the element of a List at index i
aList[i] ← aList[j] aList [i] = aList[j] Assigns value of aList[j] to aList[i]
INSERT(aList, value) aList.insert(i, value) value is placed at index i in aList. Any
element at an index greater than i will shift
one position to the right.
APPEND(aList, value) aList.append(value) adds a new item
REMOVE(aList, value) aList.pop(i)
OR
aList.remove(value)
Removes item at index i and any values at
indices greater than i shift to the left.
Length of aList decreased by 1.

Homework Assignment

Instead of us making a quiz for you to take, we would like YOU to make a quiz about the material we reviewed.

We would like you to input questions into a list, and use some sort of iterative system to print the questions, detect an input, and determine if you answered correctly. There should be at least five questions, each with at least three possible answers.

You may use the template below as a framework for this assignment.

q1 = """Which team traded Fernando Tatis Jr. to the Padres?
a. Boston Red Sox
b. Chicago White Sox
c. Cincinnati Reds
d. Seattle Mariners"""

q2 = """Which team won the NL West title in 2021?
a. Los Angeles Dodgers
b. San Diego Padres
c. San Francisco Giants
d. Arizona Diamondbacks"""

q3 = """Who hit the walk-off home run against the Cardinals which sent the Dodgers in the NLDS?
a. Chris Taylor
b. Trea Turner
c. Mookie Betts
d. Justin Turner"""

q4 = """Name the two teams in the 2019 World Series.
a. New York Yankees, Los Angeles Dodgers
b. Houston Astros, San Francisco Giants
c. Washington Nationals, Tampa Bay Rays
d. Houston Astros, Washington Nationals"""

q5 = """When did Manny Machado and Fernando Tatis Jr. make their Padres debut?
a. 2018
b. 2019
c. 2020
d. 2021"""

q6 = """Name the stadium of the Boston Red Sox.
a. Fenway Park
b. T-Mobile Park
c. Minute-Maid park
d. The Great American Ballpark"""

q7 = """Who won the 2018 AL Cy Young Award?
a. Justin Verlander
b. Patrick Corbin
c. Clayton Kershaw
d. Blake Snell"""

q8 = """In 2016, the Chicago Cubs won the World Series after how many years?
a. 56
b. 108
c. 119
d. 65"""

q9 = """Which league division are the New York Yankees in?
a. AL Central
b. NL East
c. NL West
d. AL East"""

q10 = """Which team did Brandon Drury play for?
a. San Diego Padres
b. New York Mets
c. Toronto Blue Jays
d. Arizona Diamondbacks
e. All of the above"""

questions = {q1: "b", q2: "c", q3: "a", q4: "d", q5: "b", q6: "a", q7: "d", q8: "b", q9: "d", q10: "e" }

name = input("Enter your name: ")
print(name, "how many can you get right?")
score = 0
for i in questions:
    print(i)
    ans = input("Choose the answer which you think is right.")
    if ans == questions[i]:
        print("correct!")
        score = score+1
    else:
        print("sorry, that was incorrect.")

print("Your final score is ",score)

Hacks

Here are some ideas of things you can do to make your program even cooler. Doing these will raise your grade if done correctly.

  • Add more than five questions with more than three answer choices
  • Randomize the order in which questions/answers are output
  • At the end, display the user's score and determine whether or not they passed

Challenges

Important! You don't have to complete these challenges completely perfectly, but you will be marked down if you don't show evidence of at least having tried these challenges in the time we gave during the lesson.

3.10 Challenge

Follow the instructions in the code comments.

grocery_list = ['apples', 'milk', 'oranges', 'carrots', 'cucumbers']


print(grocery_list[3])
# Now, assign the fourth item in the list to a variable, x and then print the variable
i = 3
x = grocery_list[i] 
print(x) 

# Add these two items at the end of the list : umbrellas and artichokes
grocery_list.append("umbrellas")
grocery_list.append("artichokes")

# Insert the item eggs as the third item of the list 
grocery_list.insert(2, 'eggs')

# Remove milk from the list 
grocery_list.remove('milk')

# grocery_list.pop(1)

# Assign the element at the end of the list to index 2. Print index 2 to check

grocery_list[2] = grocery_list[6]
print(grocery_list[2])
# Print the entire list, does it match ours ? 
print(grocery_list)

# Expected output
# carrots
# carrots
# artichokes
# ['apples', 'eggs', 'artichokes', 'carrots', 'cucumbers', 'umbrellas', 'artichokes']
carrots
carrots
artichokes
['apples', 'eggs', 'artichokes', 'carrots', 'cucumbers', 'umbrellas', 'artichokes']

3.8 Challenge

Create a loop that converts 8-bit binary values from the provided list into decimal numbers. Then, after the value is determined, remove all the values greater than 100 from the list using a list-related function you've been taught before. Print the new list when done.

Once you've done this with one of the types of loops discussed in this lesson, create a function that does the same thing with a different type of loop.

binarylist = [
    "01001001", "10101010", "10010110", "00110111", "11101100", "11010001", "10000001"
]
decimalist = []
def binary_convert(binary):
    decimal = 0
    i = 5
    for num in str(binary):
        if int(num) == 1:
            decimal += 2**i
            i -= 1
            continue
        else:
            i -= 1
            continue
decimalist.append(decimal)

if (binarylist) < 100:
    binarylist.pop(i)

#when done, print the results
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
/mnt/c/Users/rohan/vscode/RohanRepository/_notebooks/2022-11-26-listanditerationhomework.ipynb Cell 9 in <cell line: 16>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/rohan/vscode/RohanRepository/_notebooks/2022-11-26-listanditerationhomework.ipynb#X13sdnNjb2RlLXJlbW90ZQ%3D%3D?line=13'>14</a>             i -= 1
     <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/rohan/vscode/RohanRepository/_notebooks/2022-11-26-listanditerationhomework.ipynb#X13sdnNjb2RlLXJlbW90ZQ%3D%3D?line=14'>15</a>             continue
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/rohan/vscode/RohanRepository/_notebooks/2022-11-26-listanditerationhomework.ipynb#X13sdnNjb2RlLXJlbW90ZQ%3D%3D?line=15'>16</a> decimalist.append(decimal)
     <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/rohan/vscode/RohanRepository/_notebooks/2022-11-26-listanditerationhomework.ipynb#X13sdnNjb2RlLXJlbW90ZQ%3D%3D?line=17'>18</a> if (binarylist) < 100:
     <a href='vscode-notebook-cell://wsl%2Bubuntu/mnt/c/Users/rohan/vscode/RohanRepository/_notebooks/2022-11-26-listanditerationhomework.ipynb#X13sdnNjb2RlLXJlbW90ZQ%3D%3D?line=18'>19</a>     binarylist.pop(i)

NameError: name 'decimal' is not defined

Struggles

  • There were a few problems which I encountered when it came to naming the lists and using them in the right manner
  • How to properly use for loops
  • When I looked at other people's code there was a learning opportunity:
  • I noticed that there was a new list for the decimal values. I then saw that there was another for loop running for the original list, and that would convert it to a decimal.
  • if the decimal was over 100, that specific value was thrown out.