Python: Randomly generate and RGB Tuple

Published: 2019-09-30 17:01:40 -0400 -0400

Reading time: 1 mins (169 words)

Tags: python rgb random tutorial


I’m building a generative art program in Python and part of the process is to randomize the color I’ll be drawing with. How do I create a random RGB value in Python?


Basically you’ve just got to combine Python’s random module with a drawing library of your choice (I typically use opencv). To randomize the color, you can do something like:

import random
import time
from typing import Tuple

def generate_random_rgb_tuple(
) -> Tuple[int, int, int]:
    return (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))



The important part is just the definition of generate_random_rgb_tuple, but I’ve found it is best practice to seed your random with some value for better debugging. The output of this run, for me, was (195, 111, 116) which you can then pass to whatever RGB-compatible drawing library you want to use.

did this help?

I regularly post about tech topics I run into. You can get a periodic email containing updates on new posts and things I’ve built by subscribing here.

About the Ham

Hi I'm Hamilton and I wrote / built this! I like doing lots of things, but mostly I like to build (and then share those buildings). Some things I'm currently building: art, software, and prose. To stay up-to-date with my latest buildings, subscribe to my email list or follow one of my many other accounts. #buildit #shipit #justhamit

comments powered by Disqus