A server logs are stored as a list of tuples: `logs = [('2024-01-10', 'INFO', 'Started'), ('2024-01-10', 'ERROR', 'Disk full')]`. A developer wants to count how many ERROR logs exist. Which code snippet correctly counts them?
Trap 1: count = logs.count(('ERROR',))
list.count compares whole elements, so it searches for a one-element tuple ('ERROR',), which never matches the three-element log tuples. It is tempting because count is the obvious counting method, but it would be correct only if each element were exactly that tuple.
Trap 2: count = [log for log in logs if log[1] == 'ERROR']
This list comprehension filters matching tuples but returns the tuples themselves, not a count; len() is missing. It is tempting because the condition log[1] == 'ERROR' correctly identifies error entries, but it would be correct once wrapped in len() to produce an integer.
Trap 3: count = len(logs)
len(logs) returns the total number of log entries, including INFO records, so it ignores the ERROR filter entirely. It is tempting because len() is the standard way to count list items, but it would be correct only if every entry in the list were an ERROR log.
- A
count = logs.count(('ERROR',))
Why it fails: list.count compares whole elements, so it searches for a one-element tuple ('ERROR',), which never matches the three-element log tuples. It is tempting because count is the obvious counting method, but it would be correct only if each element were exactly that tuple.
- B
count = sum(log[1] == 'ERROR' for log in logs)
The generator expression yields a boolean per tuple, and sum() treats True as 1, counting entries whose index 1 equals 'ERROR'. This avoids manual counters and correctly handles the tuple structure, returning 1 for the sample logs.
- C
count = [log for log in logs if log[1] == 'ERROR']
Why it fails: This list comprehension filters matching tuples but returns the tuples themselves, not a count; len() is missing. It is tempting because the condition log[1] == 'ERROR' correctly identifies error entries, but it would be correct once wrapped in len() to produce an integer.
- D
count = len(logs)
Why it fails: len(logs) returns the total number of log entries, including INFO records, so it ignores the ERROR filter entirely. It is tempting because len() is the standard way to count list items, but it would be correct only if every entry in the list were an ERROR log.