pythonlistclipping

# How would I clip numbers in a list based on upper and lower limits?

Here are the instructions:

Write a function called clipnums with three parameters – a list of numbers, a upper limit number, and a lower limit number. The function should return a new list where numbers lower than lower limit are replaced by the lower limit number and numbers higher than the upper limit number are replaced by the upper limit number.

This is an intorductory course for Python so I'm just learning and am working with the basics. :)

Below is my code

def clipnums(nums, u_limit, d_limit):
newnums = []
for i in nums:
if i < d_limit:
newnums.append(d_limit)
elif i > u_limit:
newnums.append(u_limit)
else:
newnums.append(i)
return newnums


With the input

nums = [-1, 3, 0, 6, 8, 11, 20]
d_limit = 2
u_limit = 10


my code should return

[2, 3, 2, 6, 8, 10, 10]


However, it returns

[10, 10, 10, 10, 10, 2, 2]


Can anyone tell me why? Thanks!

Solution

• An easy solution could be to just use min max. This makes it a bit easier.

nums = [-1, 3, 0, 6, 8, 11, 20]
d_limit = 2
u_limit = 10

clipped_nums = [max(min(num, u_limit), d_limit) for num in nums]



To answer your question of why it doesn't work: didn't u just switch the d_limit and u_limit when calling your function?

>>> clipnums(nums, u_limit, d_limit)
[2, 3, 2, 6, 8, 10, 10]
>>> clipnums(nums, d_limit, u_limit)
[10, 10, 10, 10, 10, 2, 2]