Complete Python Series · Part 26 of 29
Assignment 13-alert-extractor
NextGen CTO — Python Assignments
A collection of practical Python exercises based on real-world scenarios from the NextGen CTO learning platform. Each assignment includes starter code, hints, a complete solution, and an explanation.
Exercise: NextGen CTO Urgent System Alert Extractor
Learn to filter system logs using list comprehensions, tuple unpacking and membership operators.
Problem statement
NextGen CTO generates logs for streaming, authentication, enrollment and payments. Build a utility that extracts messages with ERROR or WARNING severity so engineers can review urgent alerts without reading informational logs.
Task requirements
- Use the provided list of tuples containing severity and message.
- Unpack each tuple into its severity and message.
- Create
urgent_alertsusing a list comprehension that retains only messages withERRORorWARNINGseverity. - Print the resulting list in the original order.
Constraints
- Use a list comprehension, not an explicit loop or
append(). - Do not modify the original logs.
- Include messages only, not severity labels.
- Assume severity labels are uppercase.
Good luck trying the exercise!
Starter code
logs = [
("INFO", "Course streaming service started"),
("ERROR", "Database connection failed"),
("WARNING", "High memory usage on video server"),
("INFO", "Student enrollment completed"),
("ERROR", "Payment service timeout")
]
# TODO: Create urgent_alerts using a list comprehension
urgent_alerts = []
# Print the result
print(urgent_alerts)
Hints
- Unpack tuples using
for level, message in logs. - Use
level in ("ERROR", "WARNING")to test the severity. - Place the message expression before the
forclause and the filter after it.
Solution: NextGen CTO Urgent System Alert Extractor
Use a conditional list comprehension to filter the log records and extract their messages.
logs = [
("INFO", "Course streaming service started"),
("ERROR", "Database connection failed"),
("WARNING", "High memory usage on video server"),
("INFO", "Student enrollment completed"),
("ERROR", "Payment service timeout")
]
# Extract urgent alert messages using list comprehension
urgent_alerts = [
message
for level, message in logs
if level in ("ERROR", "WARNING")
]
# Print the urgent alerts
print(urgent_alerts)
Expected output
['Database connection failed', 'High memory usage on video server', 'Payment service timeout']
Solution explanation
- Lines 1–7: Define the list of log tuples, each containing a severity and a message.
- Lines 10–14: Create a new list using a comprehension. Line 11 selects the message, line 12 unpacks each tuple, and line 13 filters for ERROR or WARNING.
- Line 17: Print the resulting list of urgent messages.
Test cases
For this exercise, both ERROR and WARNING are considered urgent.