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:

  • Indexes are a way to count and organize data
  • Most start at 0
  • Collegeboard psuedocode lists start at 1
  • Numbers and lists work well for loops

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, i, 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) value is added as an element to the end of aList and length of aList is increased by 1
REMOVE(aList, i) 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.

Overview and Notes: 3.8 - Iteration

Add your OWN Notes for 3.8 here:

  • Iteration is just repetition
  • It is repeating a set of actions based on a set of conditions
  • Loops are necessary to automate functions so that there is no repetitive code
  • If a loop is not closed, it will keep repeating
  • For loops, recursive loops, and while loops are all example of iterative loops
  • They can be used to check the values in a list or automate code
  • Also nested loops, which are loops within loops

Iteration Challenge

drewpets = [("Drew", ({"dogs": 1, "cats": 1, "fish": 0}))]
ajpets = [("AJ", {"dogs": 1, "cats": 0, "fish": 329})]
johnnypets = [("Johnny", {"dogs": 2, "cats": 0, "fish": 0})]
allpets = [drewpets, ajpets, johnnypets] #a collection of all pet lists

for person in allpets:
    for name, dict in person: #unpacking the name and dictionary
        print(name + "'s pets:")
        for pet, num in dict.items(): #use .items() to go through keys and values
            print(pet.capitalize() + ":", num) #capitalizes first letter
    print("")
Drew's pets:
Dogs: 1
Cats: 1
Fish: 0

AJ's pets:
Dogs: 1
Cats: 0
Fish: 329

Johnny's pets:
Dogs: 2
Cats: 0
Fish: 0

noorcar = [("Noor", ({"brand": "mazda", "model": "CX9", "color": "white"}))]
momcar = [("Mom", {"brand": "tesla", "model": 3, "color": "white"})]
dadcar = [("Dad", {"brand": "ford", "model": "F350", "color": "brown"})]
allcars = [noorcar, momcar, dadcar] #a dictionary of the cars

for person in allcars:
    for name, dict in person: #unpacking the name and dictionary
        print(name + "'s car:")
        for car, num in dict.items(): #use .items() to go through keys and values
            print(car.capitalize() + ":", num) #capitalizes first letter
    print("")
Noor's car:
Brand: mazda
Model: CX9
Color: white

Mom's car:
Brand: tesla
Model: 3
Color: white

Dad's car:
Brand: ford
Model: F350
Color: brown

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.

import random
print("This is my homework quiz. Enter the correct letter to earn points.")

def question(prompt, answer): # automated if else statement from an early lesson
    msg = input("Question: " + prompt)
    if msg == answer:
        print(msg + " is correct")
        return(1)
    else:
        print(msg + " is not the right answer...")
        return(0)

quiz = [
    ("What is an index?",
    "A) A data structure that could store large amounts of data", 
    "B) A way to count and organize data", 
    "C) A loop within a loop",
    "D) A loop within a loop within a loop", 
    "B"),
    ("What number do collegeboard psuedocode indexes start at",
    "A) 0", 
    "B) 1", 
    "C) 40392942",
    "D) 2", 
    "B"),
    ("What does the command aList(i) = x do?",
    "A) Turn everything into x", 
    "B) Assigns the value of 'x' to the element of a list at index i", 
    "C) Removes x and location i",
    "D) Appends item x to the list", 
    "B"),
    ("What is iteration?",
    "A) repetition", 
    "B) indexing", 
    "C) suffering", 
    "D) counting",
    "A"),
    ("What is a nested loop?",
    "A) A group of indexes", 
    "B) When the elements in a loop are in the shape of a nest", 
    "C) A loop within a loop", 
    "D) A bird",
    "C"),
    ("What happens if a loop is dead?",
    "A) It will kill you too", 
    "B) Bad things", 
    "C) The loop does not begin", 
    "D) It will continue to repeat",
    "D")
]

numqs = 8
correct = 0

for item in quiz:
    num = question(item, quiz[item]) # I have been trying to debug this for hours and I keep getting the same error 
    # theoretically this code should run just fine and I'm not sure why it isn't !!!
    correct = correct + num

print("You scored" + str(correct) +"/" + str(numqs))
print("Your percentage is " + str(correct/numqs*100) + "%")
if (correct >= 6):
    print("W (you passed)")
else:
    print("L (you failed)")
This is my homework quiz. Enter the correct letter to earn points.
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/nope1013/vscode/firstrepo/_notebooks/2022-11-26-listanditerationhomework.ipynb Cell 8 in <cell line: 55>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/nope1013/vscode/firstrepo/_notebooks/2022-11-26-listanditerationhomework.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=52'>53</a> correct = 0
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/nope1013/vscode/firstrepo/_notebooks/2022-11-26-listanditerationhomework.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=54'>55</a> for item in quiz:
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/nope1013/vscode/firstrepo/_notebooks/2022-11-26-listanditerationhomework.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=55'>56</a>     num = question(item, quiz(item)) # I have been trying to debug this for hours and I keep getting the same error 
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/nope1013/vscode/firstrepo/_notebooks/2022-11-26-listanditerationhomework.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=56'>57</a>     # theoretically this code should run just fine and I'm not sure why it isn't !!!
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/nope1013/vscode/firstrepo/_notebooks/2022-11-26-listanditerationhomework.ipynb#W4sdnNjb2RlLXJlbW90ZQ%3D%3D?line=57'>58</a>     correct = correct + num

TypeError: 'list' object is not callable

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 the fourth item in the list

print(grocery_list[4])


# Now, assign the fourth item in the list to a variable, x and then print the variable

x = grocery_list[4]
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(1, "eggs")

# Remove milk from the list 

grocery_list.remove("milk")

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

grocery_list[2] = "artichokes"
print(grocery_list[2])

# Print the entire list, does it match ours ? 

print(grocery_list)

# Expected output
# cucumbers
# cucumbers
# artichokes
# ['apples', 'eggs', 'artichokes', 'carrots', 'cucumbers', 'umbrellas', 'artichokes']
cucumbers
cucumbers
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"]

final_list = []

def binary_convert(x):
    return(int(x,2))
    #use this function to convert every binary value in binarylist to decimal
    #afterward, get rid of the values that are greater than 100 in decimal
for n in binarylist:
    if binary_convert(n) <= 100: # identifying the numbers in the list that are greater than or equal to 100 so that they remain in the list
        final_list.append(n) # adding those values
        print(binary_convert(n)) # prints the values, discluding those larger than 100
73
55