Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Process a list while skipping invalid items

Safely process items in a list, skipping those that cause exceptions or can't be converted.

Python practice15 minError Handling & Edge CasesIntermediateLast updated March 20, 2026

Problem statement

Implement safe_divide_list(items, divisor) which takes an iterable of items and a divisor. For each item, attempt to convert it to a number (int or float) and divide by divisor. Collect results in a list in the same order for items that succeed. Skip items that: - cannot be converted to a number (ValueError, TypeError) - would cause ZeroDivisionError - are None Return a list of floats for successful divisions. The function must not raise exceptions for bad items; it should simply skip them.

Task

Write a function that processes a sequence but ignores invalid entries and exceptions so the program continues.

Examples

Mix of valid and invalid items

Input

safe_divide_list([10, '20', 'bad', 5], 5)

Output

[2.0, 4.0, 1.0]

10 -> 2.0, '20' -> 4.0 (converted), 'bad' skipped, 5 -> 1.0

Input format

Two arguments: an iterable of items and a divisor (number).

Output format

A list of floats containing division results for items that could be processed.

Constraints

- Do not raise for invalid items. - Use try/except to handle conversions and division errors. - Do not import external packages.

Samples

Sample 1

Input

safe_divide_list([' 15 ', None, 'x'], 3)

Output

[5.0]

' 15 ' converts to 15 then divided by 3 -> 5.0; None and 'x' are skipped.