python change the list's values based on a for loop(or other suitable method)
I need to change the list's value to 0 if the input is below 0, and change it to 255 if the input is above 255. i.e. if the list is [265,45,23], I need to change it to [255,45,0]. Tried to figure it out for hours, but gave up a bit (the initial input is a tuple). Here is my code so far, but I have no idea which logic I should use:
def rgb(r, g, b):
x = (r,g,b)
x = list(x)
for i in x:
if i<0:
x=0
if i>255:
x=255
print(x)
6 answers

When you assign to
x
you're replacing the whole variable with a new value, not just the current element of the iteration.You can use
enumerate()
to get the list index and value together, and use the index in the assignment.for i, val in enumerate(x): if val < 0: x[i] = 0 elif val > 255: x[i] = 255
You can also use a list comprehension:
x = [min(255, max(0, val)) for val in x]

You can use
max(0, min(255, x))
for a list elementx
. Then for the whole list you can use a list comprehension:x = [max(0, min(255, y)) for y in x]
Alternatively you can use the ternary operator:
x = [255 if y > 255 else (0 if y < 0 else y) for y in x]

You can use list comprehension to go through
r
,g
andb
. And at the same time create a new list that tests the conditions.def rgb(r, g, b): return [0 if x < 0 else 255 if x > 255 else x for x in (r,g,b)]
You can call it like:
print(rgb(265,45,23))
or like:
x = [265,45,23] print(rgb(*x))

Solution
def rgb(r, g, b): rgb_tuple = (r,g,b) rgb_list = list(rgb_tuple) new_list = [] for color in rgb_list: if color<0: new_list.append(0) elif color>255: new_list.append(255) else: new_list.append(color) print(new_list) return new_list rgb(266, 80, 9)

You don't need the tuple. Try this:
def rgb(r, g, b): x = [r,g,b] for i in range(len(x)): if x[i] < 0: x[i] = 0 if x[i] > 255: x[i] = 255 return x # Output: [255, 45, 0]

You could do this in a single line using a list comprehension:
def rgb(r,g,b): return [min(255,max(0,n)) for n in (r,g,b)]
Output:
rgb(265,45,23) [255, 45, 0]