easy +8 pts

Element-wise Clip

Clip each value in a list to a given minimum and maximum range.

Write a function `clip_list(values, lower, upper)` that takes a list of numbers `values` and two numbers `lower` and `upper` (with `lower <= upper`) and returns a new list where each element is: - `lower` if the element is less than `lower`, - `upper` if the element is greater than `upper`, - the element itself otherwise. The original list must remain unchanged.

Constraints

1 <= len(values) <= 1000 -10**9 <= each element, lower, upper <= 10**9 `lower` <= `upper` The function should run in O(n) time and O(n) extra space.

Example

>>> clip_list([1, 5, 10], 2, 8)
[2, 5, 8]
>>> clip_list([-5, 0, 3], -1, 1)
[-1, 0, 1]
>>> clip_list([], 0, 10)
[]
8 points ~10 min

Recent Submissions

No submissions yet — hit Run Tests to try!

Hints

Use a list comprehension to build the result.
For each value, check if it is below lower, above upper, or in range.
Python 3
All tests passed!
Test Results
Press Ctrl+Enter or click Run Tests to execute your code.