# What Won't Convert

> Some values become numbers. The rest become nothing.

Canonical URL: <https://datadriven.io/problems/what_won_t_convert>

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.

## 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**

```python
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
```

> **Time and Space Complexity**
>
> **Time:** O(n) for a single pass.
> 
> **Space:** O(n) for the result list.

> **Interviewers watch for**
>
> Catching both `ValueError` (for strings like `'abc'`) and `TypeError` (for `None`, lists, and other non-string inputs) is the tell. Candidates who catch only `ValueError` pass the string-heavy visible cases and then crash the moment a `None` shows up.

> **Common pitfall**
>
> Reaching for `str.isdigit()` as a pre-check. It rejects negatives (`'-5'` is not all digits), and it throws outright on non-string inputs because integers and `None` have no `isdigit` method. Try/except is both shorter and more correct here.

---

## Common follow-up questions

- What if you needed to cast to float instead? _(Tests swapping int() for float() and deciding whether 'inf' and 'nan' strings count as valid.)_
- What if None values should be preserved as 0 rather than left as None? _(Tests inserting a special case ahead of the try block without disturbing the failure path.)_
- How would you report which values failed conversion? _(Tests collecting the indices or values that failed alongside the converted result.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/what_won_t_convert)
- [Python Interview Questions](https://datadriven.io/python-interview-questions)
- [Data Engineering Interview Prep Guide](https://datadriven.io/data-engineer-interview-prep)
- [Daily Challenge](https://datadriven.io/daily)

---

Source: DataDriven (https://datadriven.io). DataDriven is the data engineering interview community. Live code execution in SQL, Python, and Spark sandboxes. Every feature is open to every member.