# Creats list of fruits
fruits = ["apple", "banana", "cherry", "date", "elderberry"]

# Adds item to end
fruits.append("fig")
# Changes list 

# Inserts item at a certain spot
fruits.insert(2, "grape")
# Changes list again

# Removes the first matching item
fruits.remove("date")
# Changes list for last time

# Prints updated/final list
print(fruits)
['apple', 'banana', 'grape', 'cherry', 'elderberry', 'fig']

Explanations:

  • append() adds an item (“fig”) to the end of the list.
  • insert() places an item (“grape”) at the 2nd index of the list.
  • remove() removes the first occurrence of “date” from the list.

  • Loop Type: for loop (used for iterating through all elements).
  • Structure: The loop will go through each item in the list and perform an action (e.g., printing each fruit).
# Traverses list and prints each food
for fruit in fruits:
    print(fruit)
apple
banana
grape
cherry
elderberry
fig
  • The loop iterates through the fruits list one by one.
  • For each iteration, the current item is assigned to the variable fruit, which is then printed.

Steps:

  • Start with a list of fruits
  • Traverse through each fruit
  • Apply the condition (fruit length > 5)
  • Build a new list of fruits that meet the condition
import pandas as pd

# Creates dataframe with fruits
data = {"Fruit": ["apple", "banana", "cherry", "date", "elderberry", "fig", "grape"]}
df = pd.DataFrame(data)

# Applies filter condition
filtered_fruits = df[df["Fruit"].str.len() > 5]

# Shows filtered list
print(filtered_fruits)
        Fruit
1      banana
2      cherry
4  elderberry
  • Created a DataFrame with a column Fruit containing fruit names
  • The condition .str.len() > 5 checks the length of each fruit name and filters those that are longer than 5 characters
  • The result is a new DataFrame with only the fruits that meet the condition

Reflection:

  • Filtering algorithms and lists are used in real life to organize and analyze large amounts of data
  • For example, online shopping platforms use filters to show users only items that meet specific criteria, such as price range or size.