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

10. Wildlife Survey Data Lab · Filter by Two Conditions

Use a small predicate and filter records by habitat and count.

Lesson files · lessons/search-sort-summarise/predicate-filter

Before you start
- Loop over pairs of related values.
- Use and to require two conditions.
- Clean a search string with strip() and lower().

By the end
- Filter the records to positive counts for the supplied habitat.
- Predict the result for a habitat with no matches or a record with a zero count.

Where you can use it
Show a survey team the positive sightings from one habitat by requiring both the habitat and count checks.

A predicate is a function that gives a Boolean answer about an item. Decide what counts as a match, then apply the same rule to every record. A list comprehension expresses a filter when the condition is simple. Pull longer conditions into a named helper.

Predict
Why is the last river record excluded?
- There may only be one river record.
- Its count is 0.

Worked example (example.py)

records = [("river", 2), ("ridge", 5), ("river", 0)]
print([count for habitat, count in records if habitat == "river" and count > 0])


Example result
[2]

Read a habitat. Use the example records and print a Python list of positive counts for that habitat.

Starter program (starter.py)

records = [("river", 2), ("ridge", 5), ("river", 0)]
print([count for habitat, count in records if habitat == "river" and count > 0])


Hint
Compare each record’s habitat to the cleaned input instead of the literal river.

Case 1. Try the sample
Input
 Ridge 
Expected output
[5]

Case 2. Unvisited habitat
Input
forest
Expected output
[]

Case 3. Exclude the zero count
Input
river
Expected output
[2]

Stretch
Accept a minimum count as a second input.

Reflect
What would happen if the filtering test used or instead of and?

Check your prediction
Its count is 0. and requires both the habitat and positive-count conditions.
