Skip to the content.

Lists Hacks

Tri 3 Team Teach Hacks

Homework Hack

Filtering algorithms and lists are used in real life to help organize data and display only what is useful—like filtering emails to show only unread ones. They’re used in apps, websites, and databases to make information easier to find and work with.

# ✅ 1) Create a list that includes at least five items
animals = ["dog", "cat", "elephant", "giraffe", "dolphin"]

# --- List Procedure 1: append() ---
# Adds a new item to the end of the list
animals.append("zebra")

# --- List Procedure 2: insert() ---
# Inserts an item at a specific index (here, index 2)
animals.insert(2, "lion")

# --- List Procedure 3: pop() ---
# Removes and returns the last item in the list
animals.pop()

# Show updated list
print("Updated animal list:", animals)

# 🔁 2) List Traversal Instructions:
# Traverse the list one item at a time using a for loop

print("\nTraversing the list:")
for animal in animals:
    # Access and print each animal
    print("Animal:", animal)

# 🧪 3) Filtering Algorithm using pandas
# Condition: Keep only animals with names longer than 4 letters

import pandas as pd

# Step 1: Convert list to DataFrame
df = pd.DataFrame(animals, columns=["animal"])

# Step 2: Apply condition to filter names with length > 4
filtered_df = df[df["animal"].str.len() > 4]

# Step 3: Convert filtered DataFrame back to list
long_name_animals = filtered_df["animal"].tolist()

# Print filtered result
print("\nAnimals with names longer than 4 letters:", long_name_animals)

Updated animal list: ['dog', 'cat', 'lion', 'elephant', 'giraffe', 'dolphin']

Traversing the list:
Animal: dog
Animal: cat
Animal: lion
Animal: elephant
Animal: giraffe
Animal: dolphin

Animals with names longer than 4 letters: ['elephant', 'giraffe', 'dolphin']