Transform Column
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 monitoring export hands you a column of numeric readings. Return a new column holding each reading squared, positioned the same as the reading it came from.
Same data, new shape.
Example 1
Input:
values = [1,2,3]
Output:
[1,4,9]
Example 2
Input:
values = [0]
Output:
[0]
Worked solution and explanation
What this really is
Under the 'square a column' costume this is a plain element-wise map: one transform applied to every reading, whatever the length, with each result landing where its reading sat. Anyone can multiply; what separates candidates is not assuming the shape of the visible examples. Treat the input as a few positive integers and you break on an empty export, on a two-reading export, or on fractional readings, where an int() around the product turns 1.5 squared into 2 instead of 2.25. And negatives need no special case: a number times itself is never negative, so an abs() or sign guard is noise, not a safeguard.
Break down the requirements
Step 1: Iterate through the input list
Walk the input once and square each element. A single pass is all the ordered map needs, and it works the same for zero readings or ten thousand.
Step 2: Collect results in a new list
Accumulate each squared value into a separate list you return, keeping whatever numeric type the reading had. This is also the move that keeps the caller's input intact.
The solution
def square_list(values: list) -> list:
return [val * val for val in values]A single-level comprehension: the clear idiom, one pass, a new list.
Common follow-up questions
- What if the transformation were passed in as a function parameter instead of hard-coded squaring? (Tests higher-order functions: accepting a callable and applying it.)
- How would you handle a column that contains `None` values mixed in? (Tests adding a guard to skip or replace `None` entries without crashing.)
- How does this map onto a pandas Series operation like a vectorized multiply? (Tests awareness of vectorized column operations in data libraries.)