Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Parse mixed input and collect valid values with errors

Parse a mixed list of values, extract valid numeric values, and collect detailed error records for items that cannot be parsed.

Python practice25 minError Handling & Edge CasesAdvancedLast updated March 20, 2026

Problem statement

You are given a list of mixed values (strings, numbers, None, booleans, nested containers, etc.). Build a function parse_numbers(items) that processes the list in order and attempts to convert each element to a numeric value: - Accept ints and floats (but treat booleans as invalid). - For strings: strip whitespace; an empty string is an error. Try to parse as int first, then as float. If neither works, record an error. - For None record an explicit error. For unsupported types (lists, dicts, tuples, objects) record an error noting the type name. Return a dictionary with two keys: - 'values': a list of successfully parsed numeric values (ints or floats) in the same order they appeared. - 'errors': a list of tuples (index, original_value, reason) for each item that could not be parsed. Be defensive: do not raise unhandled exceptions for bad inputs. Preserve the original value in error records so callers can inspect it later.

Task

Write a robust parser that attempts to convert mixed inputs to numbers, returns the successfully parsed values in order, and provides detailed error information (index, original value, error reason) for all failures.

Examples

Basic mixed input

Input

parse_numbers(['1', '2.5', 'x', 3, None, True])

Output

{'values': [1, 2.5, 3], 'errors': [(2, 'x', 'could not convert string to number'), (4, None, 'None'), (5, True, 'bool')]}

Strings '1' and '2.5' convert (int then float), raw int 3 accepted, 'x' fails, None and True are recorded as errors (True is treated as a boolean error).

Input format

A Python list named items containing arbitrary values (strings, numbers, None, booleans, containers, etc.).

Output format

A Python dict: {'values': [...], 'errors': [(index, original_value, reason), ...]}

Constraints

Do not raise exceptions for bad inputs. Treat booleans as invalid (they are subclasses of int in Python). Preserve original values exactly in the errors list. Do not import external libraries.

Samples

Sample 1

Input

parse_numbers([' 7 ', '', '0', '-1.0', 2.0, False])

Output

{'values': [7, 0, -1.0, 2.0], 'errors': [(1, '', 'empty string'), (5, False, 'bool')]}

Whitespace is stripped; an empty string is a recorded error; numeric strings and numeric types are accepted; False is treated as a boolean error.