• Lists are a good way to organize and collect data in a program, as they allow a set of potentially very different items to be found within one object.
  • Items in lists are located with indexes, which, in most code languages, start with 0 (though the pseudocode used by CollegeBoard usually starts at 1!).
  • Using functions like append(), pop(), and insert(), you can add new things to a list or remove them. Keeping items within lists allow you to apply a function to each item of a list using iteration.

  • Iteration is the repetition of a function. Allowing a function to repeat on its own based on various conditions can vastly optimize a program.

  • Iteration is most often done with loops, typically in combination with lists and/or dictionaries.
  • There are multiple types of loops, and while most types can, in some way, do the same thing as other types, some things are simpler to do with certain loops than others. Iteration and loops go together like bread and butter.

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:

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) added as an element to the end of a list
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:

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.

questions = [
    ("what is a list?","a set of objects"),
    ("what is an iteration", "a loop"),
    ("what functions can you use for lists and iterations", "append, pop")
]

def questionloop():
    for i in range(len(questions)):
        ans = input(i)
        if ans == (questions(i)(2)):
            print("correct")
            
questionloop()
        
---------------------------------------------------------------------------
KeyboardInterrupt                         Traceback (most recent call last)
/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb Cell 6 in <cell line: 13>()
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a>         if ans == (questions(i)(2)):
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=10'>11</a>             print("correct")
---> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=12'>13</a> questionloop()

/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb Cell 6 in questionloop()
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=6'>7</a> def questionloop():
      <a href='vscode-notebook-cell://wsl%2Bubuntu/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a>     for i in range(len(questions)):
----> <a href='vscode-notebook-cell://wsl%2Bubuntu/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a>         ans = input(i)
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a>         if ans == (questions(i)(2)):
     <a href='vscode-notebook-cell://wsl%2Bubuntu/home/shreyas/vscode/ws2/_notebooks/8-10.ipynb#W5sdnNjb2RlLXJlbW90ZQ%3D%3D?line=10'>11</a>             print("correct")

File ~/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py:1177, in Kernel.raw_input(self, prompt)
   1173 if not self._allow_stdin:
   1174     raise StdinNotImplementedError(
   1175         "raw_input was called, but this frontend does not support input requests."
   1176     )
-> 1177 return self._input_request(
   1178     str(prompt),
   1179     self._parent_ident["shell"],
   1180     self.get_parent("shell"),
   1181     password=False,
   1182 )

File ~/.local/lib/python3.8/site-packages/ipykernel/kernelbase.py:1219, in Kernel._input_request(self, prompt, ident, parent, password)
   1216             break
   1217 except KeyboardInterrupt:
   1218     # re-raise KeyboardInterrupt, to truncate traceback
-> 1219     raise KeyboardInterrupt("Interrupted by user") from None
   1220 except Exception:
   1221     self.log.warning("Invalid Message:", exc_info=True)

KeyboardInterrupt: Interrupted by user

Reflection

I made a list and iterated through it until all questions were answered and checked. I wasn't able to finish the entire thing and I messed up on the checking part.

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("umbrella")
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")

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

grocery_list[1]=grocery_list[5]

# Print the entire list, does it match ours ? 


# Expected output
# carrots
# carrots
# artichokes
# ['apples', 'eggs', 'artichokes', 'carrots', 'cucumbers', 'umbrellas', 'artichokes']
print(grocery_list)
cucumbers
cucumbers
['apples', 'umbrella', 'oranges', 'carrots', 'cucumbers', 'umbrella', '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):
    
    #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
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