Search code examples
pythontuplesgenerator

More efficient way of creating new tuple by looping over old tuple


I've managed to adjust color when cursor hovers over a tkinter canvas rounded rectangle button using this:

def shade_rgb(rgb):
    """ Adjust shade of rgb by 25% (value 64 out of 256)
        :param rgb: tuple of red, green, blue integers 0 to 255
        :returns:   tuple of red, green, blue integers 0 to 255
    """
    converted = []
    for i in rgb:
        if i < 128:
            i = i + 64
        else:
            i = i - 64
        converted.append(i)
    return tuple(converted)

I've seen code of list comprehension and tuple generators which I believe would shorten the code considerably. However I can "comprehend" how to make that work?


Reply to comment

"Where did you get stuck?"

My attempt at generator was something like this:

return tuple(i = i + 64 if i<128 else i = i - 64 for i in rgb)

Usually in Python I would use:

i = i + 64

or:

i += 64

But apparently within a generators you enter an alternate universe and the rules of physics change to:

i + 64

Solution

  • You can pass a generator expression to the tuple constructor.

    return tuple(i+64 if i<128 else i-64 for i in rgb)
    

    There's no direct syntax for a tuple comprehension, probably because tuples usually contain heterogeneous data, while lists usually contain homogeneous data.