What Won't Convert

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3

Problem

A raw export hands you a column that should be integers, but some cells hold junk that won't convert. Return the values as integers in their original order, with None in place of anything that can't be converted.

Some values become numbers. The rest become nothing.

Example 1

Input:

values = ["1","2","3"]

Output:

[1,2,3]

Example 2

Input:

values = ["10","abc","5"]

Output:

[10,null,5]

Worked solution and explanation

What this really is

Underneath the type-casting costume, this is per-element failure isolation: convert every value you can and quarantine the ones you can't as None. A single int() comprehension looks tempting until the first 'abc' throws and takes the whole list down. The trap is the except clause: catch only ValueError and you handle 'abc' but crash on None or a stray list, because those raise TypeError. Get it wrong and the function dies on the first mixed-type input instead of returning what it could salvage.


Break down the requirements

Step 1: Attempt to cast each element to int

Loop element by element so one failure never escapes past its own position. int(val) handles clean strings and truncates floats toward zero.

Step 2: Replace failures with None

Wrap each conversion in try/except and catch BOTH ValueError (strings like 'abc', '3.5') and TypeError (None, lists, other non-numeric types). Append None on failure so the output stays the same length and order as the input.


The solution

Try/except casting with None fallback
def cast_to_int(values: list) -> list:
    result = []
    for val in values:
        try:
            result.append(int(val))
        except (ValueError, TypeError):
            result.append(None)
    return result

Common follow-up questions