──────────────────────────────────────

22. The Club Library · Find Books That Match

Build a new list by keeping items that meet a condition.

Lesson files · lessons/lists-and-records/filter-a-list

Before you start
- Use append() to add an item to a list.
- Use lower() to make letters lowercase.
- Use in to check whether a character appears in text.

By the end
- Use a loop to collect matching titles in a new list.
- Use lowercase copies when you compare text.
- Test a query that matches two titles and a query that matches none.

Where you can use it
Find the workshop titles that contain a search word. Keep the original wording in the results so people see the proper titles.

Start with an empty result list. Check each title and append the original title when it matches. Use lowercase versions of both the search word and the title in the test so that STAR and star give the same results. An in test looks for the search text anywhere in the title.

After the loop, join the matches with " / ". Use an else branch to tell the reader when the result list is empty.

Predict
Which title fails the condition?
- Star Atlas
- Moon Garden

Worked example (example.py)

matches = []
for title in ["Star Map", "Moon Garden", "Star Atlas"]:
    if "Star" in title:
        matches.append(title)
print(" / ".join(matches))


Example result
Star Map / Star Atlas

Read one non-empty search word. Search the three example titles using lowercase comparisons. Print the matching titles in their original case, separated by / with one space on each side. Print No matches. if the list is empty.

Starter program (starter.py)

matches = []
for title in ["Star Map", "Moon Garden", "Star Atlas"]:
    if "Star" in title:
        matches.append(title)
print(" / ".join(matches))


Hint
Use word in title.lower() and check whether matches contains any items before calling join().

Case 1. Try the sample
Input
STAR
Expected output
Star Map / Star Atlas

Case 2. No match
Input
ocean
Expected output
No matches.

Stretch
Try requiring the search word at the start of the title with startswith().

Reflect
Why does the original list still have three titles after filtering?

Check your prediction
Moon Garden Moon Garden does not contain Star.
