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:
        if i>255:

6 answers

  • answered 2020-02-12 23:02 Barmar

    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]

  • answered 2020-02-12 23:03 a_guest

    You can use max(0, min(255, x)) for a list element x. 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]

  • answered 2020-02-12 23:04 JohanC

    You can use list comprehension to go through r, g and b. 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:


    or like:

    x = [265,45,-23]

  • answered 2020-02-12 23:04 Try Again


    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:
            elif color>255:
        return new_list
    rgb(266, 80, -9)

  • answered 2020-02-12 23:05 jws1

    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]

  • answered 2020-02-13 00:51 Alain T.

    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)]


    [255, 45, 0]