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:

Notes

  • lists are collections of data
    • indexes: most code languages count starting with zero, and this is also the case for list indexes
    • you can use them to store unlimited amounts of data
  • loops/functions that locate list data using indexes can perform specific functions on lists
  • List indexes start with 0 generally
  • Numbers in list can be used for math

Table

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

  • repetition
  • copy pasting the same code is complicated and unprofessional
    • conditional iteration: you need to tell the machine when to stop
  • most languages have their own versions of a "for" loop
  • lists can have multiple items and you may need multiple parenthesis with different variables in the list
    • dictionaries are useful here
  • recursive loops can be created in multiple ways and involve incrementing a varaible until it reaches a certain breaking point
  • while loops don't require a function that is then called again within the original function until a condition is met
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

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.

right = 0 
totalqs = 5 

questions = [
    ("What do list indexes generally start with","A) 0", "B) 1", "C) -1", "A"),
    ("What is iteration known as?", "A) Looping", "B) Repetition", "C) Stringing", "B"),
    ("What does aList[i] do?","A) Accesses the element of aList at index i", "B) Assigns the element of aList at index i <br>to a variable 'x'", "C) _Assigns value of aList[j] to aList[i]_", "A"),
    ("What can numbers in lists be used for?", "A) Reading", "B) Science", "C) Math", "C"),
    ("What are lists?", "A) A sequence of characters", "B) Collection of data", "C) A repetition of code until the desired result is produced", "B")
]
#

# After attempting to try the quiz, it doesn't seem to work. I think there is something wrong with my integer and position placement, but I don't understand how to fix it. 
def questionloop():
    right = 0
    for i in range(len(questions)):
        answer = input("A, B, or C")
        if answer == questions[4]: # 4 represents position in lsit
            print("Correct")
            right = right + 1
        else:
            print("Wrong") 
questionloop()

print("You got a: " + str(right) + "/5" + " or a " + str((right/totalqs)*100) + "%")

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 = grocery_list + ["umbrellas", "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')

# Assign the element at the end of the list to index 2. Print index 2 to check
grocery_list[2] = grocery_list[-1]
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"
]

def binary_convert(binary):
    return int(binary, 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
binarylist = [i for i in binarylist if binary_convert(i)<100]
#when done, print the results
binarylist
['01001001', '00110111']