Filtering Tables
Now that you’ve seen how to use if
, elif
, and else
, let’s apply conditions to something more realistic — like filtering rows in a table (represented as a list of lists).
Imagine you have a dataset like this:
students = [
["Name", "Score"],
["Alice", 85],
["Bob", 59],
["Charlie", 72],
["Diana", 91],
["Eve", 66]
]
Suppose we want to create a new table that only contains students who scored 70 or more.
Filtering Logic
We can loop through the list and use an if
condition to check each score:
# Remove the header before filtering
filtered = [["Name", "Score"]]
for row in students[1:]:
name = row[0]
score = row[1]
if score >= 70:
filtered.append([name, score])
print(filtered)
Output
[['Name', 'Score'], ['Alice', 85], ['Charlie', 72], ['Diana', 91]]
Using Nested Lists and if
Tables are just lists of lists. We can filter based on any condition, such as:
- Score above a threshold
- Names starting with a letter
- Even vs. odd numbers
- Matching a specific word or keyword
Here is an example:
# Students who failed (score below 60)
failed = [["Name", "Score"]]
for row in students[1:]:
if row[1] < 60:
failed.append(row)
print(failed)
Output
[['Name', 'Score'], ['Bob', 59]]
Exercise: Try It Yourself!
Write a Python program that takes the following list of employees and filters out only those with a salary greater than 50,000.
Your Output Should Be:
[['Name', 'Salary'], ['Lily', 52000], ['John', 60000]]
Tip: Use a for
loop to go through employees[1:]
, and check if salary > 50000
.