# Type Caster

> Wrong type. Fix it.

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

Domain: Python · Difficulty: easy · Seniority: L3

## Problem

Given a list of values, return a new list where each element is the result of int(value). Any element that raises when cast becomes None instead. Preserve input order.

## Worked solution and explanation

### Why this problem exists in real interviews

This tests **defensive type conversion** with error handling. Pipeline inputs often arrive as strings that need casting, and the ability to handle failures gracefully with try/except is a basic but important skill.

---

### Break down the requirements

#### Step 1: Attempt to cast each element to int

Use `int(val)` for the conversion.

#### Step 2: Replace failures with None

Wrap each conversion in try/except to catch `ValueError` and `TypeError`.

---

### 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 types like `None` or `list`) shows defensive coding habits.

> **Common Pitfall**
>
> Using `str.isdigit()` as a pre-check. This misses negative numbers (`'-5'`) and fails for non-string inputs. Try/except is more robust.

---

## Common follow-up questions

- What if you needed to cast to float instead? _(Tests swapping `int()` for `float()` and handling 'inf' or 'nan' strings.)_
- What if None values should be preserved as 0 instead? _(Tests adding a special case before the try block.)_
- How would you log which values failed conversion? _(Tests adding logging or collecting error indices alongside the result.)_

## Related

- [All practice problems](https://datadriven.io/problems)
- [Mock interview mode](https://datadriven.io/interview/type_caster)
- [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). 100% free data engineering interview prep. Live code execution against Postgres 16, Python 3.11, and Spark sandboxes. No paywall, no premium tier, no signup gate.