Practical Example: Filtering High CPU Servers

๐Ÿท๏ธ Lists and List Operations / List Comprehensions


๐Ÿ” Context Introduction

Imagine you're monitoring a fleet of servers and need to quickly identify which ones are running at dangerously high CPU levels. You have a list of server names and their corresponding CPU usage percentages. Instead of manually scanning through the data, you can use Python's list comprehensions to instantly filter out only the servers that exceed a certain threshold. This is a common real-world scenario where list operations save time and reduce human error.


โš™๏ธ The Problem Setup

We have two parallel lists:

  • Server names: A list of strings identifying each machine.
  • CPU usage: A list of numbers representing the current CPU percentage for each server.

Our goal is to extract only the servers where CPU usage is above 80%.

Example Data:

  • Server names: web-server-01, db-server-02, cache-node-03, app-server-04, monitor-host-05
  • CPU usage: 75, 92, 88, 45, 96

๐Ÿ› ๏ธ The Traditional Approach (Without List Comprehension)

Before using list comprehensions, an engineer might write a loop to build a new list manually:

  • Create an empty list called high_cpu_servers.
  • Use a for loop with range() to iterate over the index positions.
  • Inside the loop, check if the CPU value at that index is greater than 80.
  • If true, append the corresponding server name to the new list.
  • Print the result.

This works, but it requires multiple lines of code and is more prone to small mistakes like off-by-one errors.


๐Ÿš€ The List Comprehension Solution

A list comprehension achieves the same result in a single, readable line. Here's how it breaks down:

Syntax Structure:

  • Start with square brackets [] to create a new list.
  • Inside, write the expression for what you want to include (the server name).
  • Then write the for clause to iterate over the data.
  • Finally, add an if condition to filter only the items you need.

For our example:

  • Expression: server_names[i] (the server name at the current index)
  • For clause: for i in range(len(cpu_usage)) (loop over all index positions)
  • If condition: if cpu_usage[i] > 80 (only include if CPU is above threshold)

The result is a new list containing: db-server-02, cache-node-03, monitor-host-05


๐Ÿ“Š Comparison: Loop vs. List Comprehension

Aspect Traditional Loop List Comprehension
Lines of code 4โ€“5 lines 1 line
Readability Clear but verbose Concise and expressive
Performance Slightly slower Faster (optimized in C)
Error potential Higher (indexing mistakes) Lower (less code to debug)
Best use case Complex logic inside loop Simple filtering or transformation

๐Ÿ•ต๏ธ Breaking Down the Comprehension Step by Step

Let's walk through what happens when Python executes this list comprehension:

  1. Python starts the for loop, setting i to 0.
  2. It checks the if condition: cpu_usage[0] is 75. Is 75 > 80? No, so skip.
  3. Next iteration: i = 1. cpu_usage[1] is 92. Is 92 > 80? Yes. Add server_names[1] to the new list.
  4. Next: i = 2. cpu_usage[2] is 88. Is 88 > 80? Yes. Add server_names[2].
  5. Next: i = 3. cpu_usage[3] is 45. Is 45 > 80? No, skip.
  6. Next: i = 4. cpu_usage[4] is 96. Is 96 > 80? Yes. Add server_names[4].
  7. Loop ends. The new list now contains three server names.

๐Ÿงช Testing with Different Thresholds

You can easily change the filtering condition without rewriting the entire logic:

  • To find servers with CPU exactly at 100%: Change condition to cpu_usage[i] == 100
  • To find servers with CPU below 50%: Change condition to cpu_usage[i] < 50
  • To find servers with CPU between 70 and 90: Use 70 < cpu_usage[i] < 90

This flexibility makes list comprehensions extremely practical for dynamic monitoring scripts.


๐Ÿ“ Key Takeaways for Engineers

  • List comprehensions are not just for simple math; they excel at filtering real-world data.
  • The pattern expression + for + if is reusable across many scenarios, not just server monitoring.
  • When working with parallel lists, always ensure both lists have the same length to avoid index errors.
  • For more complex filtering (multiple conditions), you can chain if statements or use and / or inside the condition.

๐ŸŽฏ Final Thought

Mastering list comprehensions transforms how you process data in Python. What once required a loop with multiple lines now becomes a single, expressive statement. For any engineer dealing with lists of metrics, logs, or configurations, this tool is indispensable for writing clean, efficient, and maintainable code.


This example shows how to use list comprehensions to filter server CPU data and identify high-usage machines.

๐Ÿ”ง Example 1: Basic list comprehension to extract CPU values

This example creates a simple list of CPU percentages from server data.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]

high_cpu = [cpu for cpu in cpu_usage if cpu > 80]
print(high_cpu)

๐Ÿ“ค Output: [82, 91]


๐Ÿ”ง Example 2: Filtering server names with high CPU

This example pairs server names with their CPU usage and filters only the high-usage servers.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]

high_cpu_servers = [servers[i] for i in range(len(servers)) if cpu_usage[i] > 80]
print(high_cpu_servers)

๐Ÿ“ค Output: ['web02', 'db01']


๐Ÿ”ง Example 3: Creating a list of tuples with server and CPU data

This example builds a list of (server, cpu) pairs for all servers with CPU over 75%.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]

high_cpu_pairs = [(servers[i], cpu_usage[i]) for i in range(len(servers)) if cpu_usage[i] > 75]
print(high_cpu_pairs)

๐Ÿ“ค Output: [('web02', 82), ('db01', 91)]


๐Ÿ”ง Example 4: Filtering with multiple conditions (CPU and memory)

This example filters servers where both CPU is high and memory usage is also high.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]
memory_usage = [60, 78, 95, 50, 72]

critical_servers = [servers[i] for i in range(len(servers)) if cpu_usage[i] > 80 and memory_usage[i] > 75]
print(critical_servers)

๐Ÿ“ค Output: ['db01']


๐Ÿ”ง Example 5: Practical alert generation with custom messages

This example generates alert messages for servers exceeding CPU thresholds.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]

alerts = [f"ALERT: {servers[i]} CPU at {cpu_usage[i]}%" for i in range(len(servers)) if cpu_usage[i] > 80]
for alert in alerts:
    print(alert)

๐Ÿ“ค Output: ALERT: web02 CPU at 82%
ALERT: db01 CPU at 91%


๐Ÿ“Š Comparison Table: Filtering Methods

Method Use Case Code Complexity Readability
Basic list comprehension Simple filter on values Low High
Index-based filter Filter with paired data Medium Medium
Tuple creation Group related data Medium High
Multiple conditions Complex filtering Medium Medium
Alert generation Practical output Medium High

๐Ÿ” Context Introduction

Imagine you're monitoring a fleet of servers and need to quickly identify which ones are running at dangerously high CPU levels. You have a list of server names and their corresponding CPU usage percentages. Instead of manually scanning through the data, you can use Python's list comprehensions to instantly filter out only the servers that exceed a certain threshold. This is a common real-world scenario where list operations save time and reduce human error.


โš™๏ธ The Problem Setup

We have two parallel lists:

  • Server names: A list of strings identifying each machine.
  • CPU usage: A list of numbers representing the current CPU percentage for each server.

Our goal is to extract only the servers where CPU usage is above 80%.

Example Data:

  • Server names: web-server-01, db-server-02, cache-node-03, app-server-04, monitor-host-05
  • CPU usage: 75, 92, 88, 45, 96

๐Ÿ› ๏ธ The Traditional Approach (Without List Comprehension)

Before using list comprehensions, an engineer might write a loop to build a new list manually:

  • Create an empty list called high_cpu_servers.
  • Use a for loop with range() to iterate over the index positions.
  • Inside the loop, check if the CPU value at that index is greater than 80.
  • If true, append the corresponding server name to the new list.
  • Print the result.

This works, but it requires multiple lines of code and is more prone to small mistakes like off-by-one errors.


๐Ÿš€ The List Comprehension Solution

A list comprehension achieves the same result in a single, readable line. Here's how it breaks down:

Syntax Structure:

  • Start with square brackets [] to create a new list.
  • Inside, write the expression for what you want to include (the server name).
  • Then write the for clause to iterate over the data.
  • Finally, add an if condition to filter only the items you need.

For our example:

  • Expression: server_names[i] (the server name at the current index)
  • For clause: for i in range(len(cpu_usage)) (loop over all index positions)
  • If condition: if cpu_usage[i] > 80 (only include if CPU is above threshold)

The result is a new list containing: db-server-02, cache-node-03, monitor-host-05


๐Ÿ“Š Comparison: Loop vs. List Comprehension

Aspect Traditional Loop List Comprehension
Lines of code 4โ€“5 lines 1 line
Readability Clear but verbose Concise and expressive
Performance Slightly slower Faster (optimized in C)
Error potential Higher (indexing mistakes) Lower (less code to debug)
Best use case Complex logic inside loop Simple filtering or transformation

๐Ÿ•ต๏ธ Breaking Down the Comprehension Step by Step

Let's walk through what happens when Python executes this list comprehension:

  1. Python starts the for loop, setting i to 0.
  2. It checks the if condition: cpu_usage[0] is 75. Is 75 > 80? No, so skip.
  3. Next iteration: i = 1. cpu_usage[1] is 92. Is 92 > 80? Yes. Add server_names[1] to the new list.
  4. Next: i = 2. cpu_usage[2] is 88. Is 88 > 80? Yes. Add server_names[2].
  5. Next: i = 3. cpu_usage[3] is 45. Is 45 > 80? No, skip.
  6. Next: i = 4. cpu_usage[4] is 96. Is 96 > 80? Yes. Add server_names[4].
  7. Loop ends. The new list now contains three server names.

๐Ÿงช Testing with Different Thresholds

You can easily change the filtering condition without rewriting the entire logic:

  • To find servers with CPU exactly at 100%: Change condition to cpu_usage[i] == 100
  • To find servers with CPU below 50%: Change condition to cpu_usage[i] < 50
  • To find servers with CPU between 70 and 90: Use 70 < cpu_usage[i] < 90

This flexibility makes list comprehensions extremely practical for dynamic monitoring scripts.


๐Ÿ“ Key Takeaways for Engineers

  • List comprehensions are not just for simple math; they excel at filtering real-world data.
  • The pattern expression + for + if is reusable across many scenarios, not just server monitoring.
  • When working with parallel lists, always ensure both lists have the same length to avoid index errors.
  • For more complex filtering (multiple conditions), you can chain if statements or use and / or inside the condition.

๐ŸŽฏ Final Thought

Mastering list comprehensions transforms how you process data in Python. What once required a loop with multiple lines now becomes a single, expressive statement. For any engineer dealing with lists of metrics, logs, or configurations, this tool is indispensable for writing clean, efficient, and maintainable code.

Interactive Views

You are currently in ๐Ÿ“š All-in-One mode. Use the tabs at the top to switch to ๐Ÿ“– Theory Only or ๐Ÿ’ป Code Only views.

This example shows how to use list comprehensions to filter server CPU data and identify high-usage machines.

๐Ÿ”ง Example 1: Basic list comprehension to extract CPU values

This example creates a simple list of CPU percentages from server data.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]

high_cpu = [cpu for cpu in cpu_usage if cpu > 80]
print(high_cpu)

๐Ÿ“ค Output: [82, 91]


๐Ÿ”ง Example 2: Filtering server names with high CPU

This example pairs server names with their CPU usage and filters only the high-usage servers.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]

high_cpu_servers = [servers[i] for i in range(len(servers)) if cpu_usage[i] > 80]
print(high_cpu_servers)

๐Ÿ“ค Output: ['web02', 'db01']


๐Ÿ”ง Example 3: Creating a list of tuples with server and CPU data

This example builds a list of (server, cpu) pairs for all servers with CPU over 75%.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]

high_cpu_pairs = [(servers[i], cpu_usage[i]) for i in range(len(servers)) if cpu_usage[i] > 75]
print(high_cpu_pairs)

๐Ÿ“ค Output: [('web02', 82), ('db01', 91)]


๐Ÿ”ง Example 4: Filtering with multiple conditions (CPU and memory)

This example filters servers where both CPU is high and memory usage is also high.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]
memory_usage = [60, 78, 95, 50, 72]

critical_servers = [servers[i] for i in range(len(servers)) if cpu_usage[i] > 80 and memory_usage[i] > 75]
print(critical_servers)

๐Ÿ“ค Output: ['db01']


๐Ÿ”ง Example 5: Practical alert generation with custom messages

This example generates alert messages for servers exceeding CPU thresholds.

servers = ["web01", "web02", "db01", "app01", "cache01"]
cpu_usage = [45, 82, 91, 67, 55]

alerts = [f"ALERT: {servers[i]} CPU at {cpu_usage[i]}%" for i in range(len(servers)) if cpu_usage[i] > 80]
for alert in alerts:
    print(alert)

๐Ÿ“ค Output: ALERT: web02 CPU at 82%
ALERT: db01 CPU at 91%


๐Ÿ“Š Comparison Table: Filtering Methods

Method Use Case Code Complexity Readability
Basic list comprehension Simple filter on values Low High
Index-based filter Filter with paired data Medium Medium
Tuple creation Group related data Medium High
Multiple conditions Complex filtering Medium Medium
Alert generation Practical output Medium High