Skip to the content.

Lists & Filtering Algorithms HW Hack

Popcorn Hack 1

What are some possible benefits of using lists? What are some real world examples of lists being used in code? Some possible benefits of using lists are that they can be used to store and manipulate collections of data. It is much more efficient and organized than creating multiple variables to store individual elements. Lists can also be used to create dynamic data structures that can be easily modified. A real lifeexample of a list is a playlist of songs on Spotify.

Popcorn Hack 2

What does this code output? The code outputs eraser. First, it removes pencil leaving ["pen", "marker", "eraser"] . Then it appends sharpener, making it the last item in the list: ["pen", "marker", "eraser", "sharpener"] . Then it prints the word on the second index which is "eraser"

items = ["pen", "pencil", "marker", "eraser"]
items.remove("pencil")
items.append("sharpener")
print(items[2])
eraser

Popcorn Hack 3

What are some real world examples of filtering algorithms? A real world example of a filtering algorithm would be a search engine, as it filters data through what you’re inputting in the search and returns the values matching your search. Another example would be a spam filter on an email account, as it filters out unwanted emails from your inbox.

Homework Hacks:

1. Create a list that includes at least five items. Use at least three different list procedures: Label with comments where each list procedure is used and explain what it’s doing.

fruits = ["apple", "banana", "cherry", "strawberry", "kiwi"]
fruits.remove("banana") # remove the second item, "banana".
fruits.append("orange") # adds "orange" to the end of the list.
print(fruits[3]) # prints the fourth item (third index), "kiwi".
kiwi

2. Write the steps for how you would go through your list one item at a time. Clearly describe how the traversal happens (loop type and structure).

To go through the items of my list one by one, I would iterate through it using a for loop. Here is the structure:

fruits = ["apple", "banana", "cherry", "strawberry", "kiwi"]
for i in fruits:
    print(i) # prints each item in the list.
apple
banana
cherry
strawberry
kiwi

3. Filtering Algorithm (Use pandas - database filtering) Instructions:

  • Choose a condition
  • Write out the steps you would take to:
  • Start with a list
  • Go through each item (traversal)
  • Apply your condition
import pandas as pd

data = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 35},
    {'name': 'Charlie', 'age': 30},
    {'name': 'Diana', 'age': 40}
]

# Convert list into a DataFrame
df = pd.DataFrame(data)

filtered_df = df[df['age'] > 30]

print(filtered_df)
    name  age
1    Bob   35
3  Diana   40