It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Python Basics

Course by zooboole,

Last Updated on 2025-02-26 16:14:49

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.