Alim '
Alim '

Reputation: 33

How to add a value to an RGB tuple?

I want to make a colour brighter by adding an integer to each RGB value of the variable but im not sure how to do it.

black = (0,0,0)

for i in black:
   black[i] += 50

print(black)

The expected output is (50, 50, 50)

Upvotes: 0

Views: 870

Answers (2)

Shivam Seth
Shivam Seth

Reputation: 687

Tuples are immutable

If your code needs to change value of RGB dynamically, then preferred datatype is List

So use list instead:

black = [0,0,0]

for i in range(len(black)):
   black[i] += 50

print(black)
op:[50, 50, 50]

Note:If you use your code by just change tuple to list, Then you will get [150, 0, 0] instead [50, 50, 50], Because value of i will be 0 all 3 times, and for next run you will get runTime error

Upvotes: 0

Omer Tuchfeld
Omer Tuchfeld

Reputation: 3022

Tuples are immutable, you cannot change their values after they are created. Try creating a new tuple instead:

black = (0,0,0)

newcolor = (black[0] + 50, black[1] + 50, black[2] + 50)

print(newcolor)

Or with list comprehension:

black = (0,0,0)

newcolor = tuple(component + 50 for component in black)

print(newcolor)

Remember you can only max each component to 255 - use Saturation arithmetic to overcome this

Upvotes: 2

Related Questions