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: Collections that store data, can use loops to iterate through them

Python: list name = [element 1 , element 2 ]

  • Index: Specify the location where a list element is found, usually starts at 0 Note: In AP CSP, list indexes start at 1

Example: myList = [0, 1, 2]

print(myList[0]) will output 0


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:

Use iteration to simplify your code and to prevent manually repeating code over and over again.

Iteration:

While loop: while condition:

See the code cell below for an example of iterating through a list using a while loop.

myList = ["apples", "oranges", "bananas"]

i = 0
while i < len(myList):
    print(myList[i])
    i += 1
apples
oranges
bananas

For loop (iterate through lists): for element name in list name:

Recursive loop: Recursive loops call themselves by calling the function name again

Note: Don't do the code below, will run forever

def recursive_function():
    recursive_function


You can put a dictionary in a list, below is an example:

Note: When you are printing a dictionary by its key, specify the key name in brackets [].

Example: myList = {"myKey":"myValue"}, to print out the value, do: print(myList["myKey"])

myList = [{1: "red", 2: "blue"}, {1: "purple", 2: "green"}]

print("Printing the first dictionary in myList: " + str(myList[0]))
print("Printing the second dictionary in myList: " + str(myList[1]))

print("Printing the second key in the first dictionary in myList: " + str(myList[0][2]))
Printing the first dictionary in myList: {1: 'red', 2: 'blue'}
Printing the second dictionary in myList: {1: 'purple', 2: 'green'}
Printing the second key in the first dictionary in myList: blue


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.


Ver 1

Below is my quiz that does not use randomization. It has 6 questions, and some questions have more than 3 answer choices. At the end of the quiz, a score will be displayed with a message saying whether the user has passed or not.

questions = [
    "What is the method that adds an element to the end of the list?",
    "What is a method that can be used to edit a list?", 
    "T/F: Lists can contain many items in the form of tuples or hash maps.", 
    "Give an example of an iteration loops",
    "Refer to the following list: [1, 2, 7, 3, 10]. What index contains an odd number?",
    "Write out the code that will create a list called \"myList\" and store the numbers: 1, 2, 3 (you can write it in any order)"
]

answers = [["append", ".append", ".append()"],  
["insert", "append", "remove"], 
["T", "true", "True"], 
["for", "recursion", "while"], 
["0", "2", "3", "zero", "two", "three", "Zero", "Two", "Three"],
["myList = [1, 2, 3]", "myList = [1, 3, 2]","myList = [2, 1, 3]","myList = [2, 3, 1]","myList = [3, 1, 2]","myList = [3, 2, 1]"]
]

number = 0
score = 0

def questionloop():
    for question in questions:
        global number 
        print(question)
        usrAnswer = input("Enter answer:")
        print("Enter answer: " + usrAnswer)
        answercheck(usrAnswer)
        number += 1
    print("Your score is: " + str(score) + "/" + str(len(questions)))
    if score/len(questions) >= 0.7:
        print("Congrats! You passed!")
    else:
        print("You did not pass. Try again.")
    
    # IMPORTANT: rem pass

def answercheck(usrAnswer):
    for i in range (0, len(answers[number])):
        if usrAnswer == answers[number][i]:
            print("Correct!")
            global score
            score += 1
            return
    print("Incorrect!")
    
questionloop()
What is the method that adds an element to the end of the list?
Enter answer: .append
Correct!
What is a method that can be used to edit a list?
Enter answer: remove
Correct!
T/F: Lists can contain many items in the form of tuples or hash maps.
Enter answer: wrong answer
Incorrect!
Give an example of an iteration loops
Enter answer: for
Correct!
Refer to the following list: [1, 2, 7, 3, 10]. What index contains an odd number?
Enter answer: Zero
Correct!
Write out the code that will create a list called "myList" and store the numbers: 1, 2, 3 (you can write it in any order)
Enter answer: myList = [3, 2, 1]
Correct!
Your score is: 5/6
Congrats! You passed!

Ver #2

In this version of the quiz, I imported the random library to randomize the questions. All of the other features remain the same.

import random

questions = [
    "What is the method that adds an element to the end of the list?",
    "What is a method that can be used to edit a list?", 
    "T/F: Lists can contain many items in the form of tuples or hash maps.", 
    "Give an example of an iteration loops",
    "Refer to the following list: [1, 2, 7, 3, 10]. What index contains an odd number?",
    "Write out the code that will create a list called \"myList\" and store the numbers: 1, 2, 3 (you can write it in any order)"
]

answers = [["append", ".append", ".append()"],  
["insert", "append", "remove"], 
["T", "true", "True"], 
["for", "recursion", "while"], 
["0", "2", "3", "zero", "two", "three", "Zero", "Two", "Three"],
["myList = [1, 2, 3]", "myList = [1, 3, 2]","myList = [2, 1, 3]","myList = [2, 3, 1]","myList = [3, 1, 2]","myList = [3, 2, 1]"]
]


order = random.sample(range(0, len(questions)), len(questions)) 

for i in range (0, len(questions)):
    storage = questions[i] 
    storageAnswer = answers[i]
    questions[i] = questions[order[i]]
    answers[i] = answers[order[i]]
    questions[order[i]] = storage
    answers[order[i]] = storageAnswer

number = 0  
score = 0



def questionloop():
    for question in questions:
        global number 
        print(question)
        usrAnswer = input(question)
        print("Enter answer: " + usrAnswer)
        answercheck(usrAnswer)
        number += 1
    print("Your score is: " + str(score) + "/" + str(len(questions)))
    if score/len(questions) >= 0.7:
        print("Congrats! You passed!")
    else:
        print("You did not pass. Try again.")
    

def answercheck(usrAnswer):
    for i in range (0, len(answers[number])):
        if usrAnswer == answers[number][i]:
            print("Correct!")
            global score
            score += 1
            return
    print("Incorrect!")
    
questionloop()
What is a method that can be used to edit a list?
Enter answer: remove
Correct!
What is the method that adds an element to the end of the list?
Enter answer: .append
Correct!
Give an example of an iteration loops
Enter answer: for
Correct!
Refer to the following list: [1, 2, 7, 3, 10]. What index contains an odd number?
Enter answer: Zero
Correct!
T/F: Lists can contain many items in the form of tuples or hash maps.
Enter answer: wrong answer
Incorrect!
Write out the code that will create a list called "myList" and store the numbers: 1, 2, 3 (you can write it in any order)
Enter answer: myList = [3, 2, 1]
Correct!
Your score is: 5/6
Congrats! You passed!

Extra

Below is the quiz that I made with JavaScript. You can go forward and backwards to try out different questions, and you can type in answer. The check button will give you feedback on if your answer is right or wrong.



This is my code:


<p id="question"></p>

<input type="text" id="answerBox">

<button onclick="check()">Check</button>
<br>
<br>
<button onclick="backQuestion()">Back</button>
<button onclick="nextQuestion()">Next</button>

<p id="feedback"></p>

<script>
    let questions = ["What is the method that adds an element to the end of the list?",
    "What is a method that can be used to edit a list?", 
    "T/F: Lists can contain many items in the form of tuples or hash maps.", 
    "Give an example of an iteration loop",
    "Refer to the following list: [1, 2, 7, 3, 10]. What index contains an odd number?",
    "Write out the code that will create a list called \"myList\" and store the numbers: 1, 2, 3 (you can write it in any order)"
    ];

    let answers = [["append", ".append()", ".append"],
    ["insert", "append", "remove"],
    ["T", "true", "True"], 
    ["for", "recursion", "while"], 
    ["0", "2", "3", "zero", "two", "three", "Zero", "Two", "Three"],
    ["myList = [1, 2, 3]", "myList = [1, 3, 2]","myList = [2, 1, 3]","myList = [2, 3, 1]","myList = [3, 1, 2]","myList = [3, 2, 1]"]
    ];

    let i = 0; 
    document.getElementById("question").innerHTML = questions[0]; 

    function nextQuestion() {

        if (i < questions.length - 1){
            document.getElementById("feedback").innerHTML = ""; 
            document.getElementById("answerBox").value = ""; 
            i++;
        }
        document.getElementById("question").innerHTML = questions[i]; 
    }

    function backQuestion() {

        if (i > 0){
            document.getElementById("feedback").innerHTML = ""; 
            document.getElementById("answerBox").value = ""; 
            i--;
        }
        document.getElementById("question").innerHTML = questions[i]; 
    }

    function check() {
        var response = document.getElementById("answerBox").value;
        for (let multiA = 0; multiA < answers[i].length; multiA++) {
            if (response == answers[i][multiA]) {
                document.getElementById("feedback").innerHTML = "Correct";
                return;
            } 
        }

        document.getElementById("feedback").innerHTML = "Incorrect";
    }

</script>

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[3])

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

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


# 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")

# Assign the element at the end of the list to index 2. Print index 2 to check
grocery_list[2] = grocery_list[6]

# 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
artichoke
['apples', 'eggs', 'artichoke', 'carrots', 'cucumbers', 'umbrellas', 'artichoke']

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"
]

decimalList = []

def binary_convert(binary):
    sum = 0; 

    for binaryNum in binarylist: 
        for i in range (0, 8): 
            binaryDigit = binaryNum[i:i + 1:1]
            if binaryDigit == "1":
                sum += 2 ** (7 - i)
        decimalList.append(sum)
        sum = 0
            
                
    #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

#when done, print the results

binary_convert(binarylist)

for decimalNum in decimalList: 
    if decimalNum < 100: 
        decimalList.remove(decimalNum)

print(decimalList)
[170, 150, 236, 209, 129]