Generating a Range of "n" Colors

Let's say you want to generate a list of colors (be it in RGB or hexadecimal representation) that span across a color spectrum of n entries. How do you do it?

First, install colour by calling pip install colour.

Next, run this code, which assumes that you want a range of ten colors (i.e. n = 10).

from colour import Color
red = Color('red')
blue = Color('blue')
color_range = list(red.range_to(blue, 10))
print(color_range)

This gives you a list of Color objects, ten of them to be exact:

[<Color red>, <Color #ff7100>, <Color #ffe300>, <Color #af0>, <Color #39ff00>, <Color #00ff39>, <Color #0fa>, <Color #00e3ff>, <Color #0071ff>, <Color blue>]

To extract the rgb or hex values from a single Color object, simply do the following:

c = color_range[1]
print('RGB: {}'.format(c.get_rgb()))
print('HEX: {}'.format(c.get_hex()))

Here's the corresponding output:

RGB: (1.0, 0.4444444444444444, 0.0)
HEX: #ff7100

Codes, In a Nutshell

Now, why stop there? Let's turn it into a reusable function.

from colour import Color

def get_color_range(n, output_type='hex'):
    red = Color('red')
    blue = Color('blue')
    color_range = list(red.range_to(blue, n))
    if output_type == 'hex':
        return [c.get_hex_l() for c in color_range]
    else:
        return [c.get_rgb() for c in color_range]
print(get_color_range(100))

This gives you 100 hexadecimal color representations:

['#ff0000', '#ff0a00', '#ff1500', '#ff1f00', '#ff2900', '#ff3400', '#ff3e00', '#ff4800', '#ff5200', '#ff5d00', '#ff6700', '#ff7100', '#ff7c00', '#ff8600', '#ff9000', '#ff9b00', '#ffa500', '#ffaf00', '#ffb900', '#ffc400', '#ffce00', '#ffd800', '#ffe300', '#ffed00', '#fff700', '#fcff00', '#f2ff00', '#e8ff00', '#deff00', '#d3ff00', '#c9ff00', '#bfff00', '#b4ff00', '#aaff00', '#a0ff00', '#95ff00', '#8bff00', '#81ff00', '#76ff00', '#6cff00', '#62ff00', '#58ff00', '#4dff00', '#43ff00', '#39ff00', '#2eff00', '#24ff00', '#1aff00', '#0fff00', '#05ff00', '#00ff05', '#00ff0f', '#00ff1a', '#00ff24', '#00ff2e', '#00ff39', '#00ff43', '#00ff4d', '#00ff58', '#00ff62', '#00ff6c', '#00ff76', '#00ff81', '#00ff8b', '#00ff95', '#00ffa0', '#00ffaa', '#00ffb4', '#00ffbf', '#00ffc9', '#00ffd3', '#00ffde', '#00ffe8', '#00fff2', '#00fffc', '#00f7ff', '#00edff', '#00e3ff', '#00d8ff', '#00ceff', '#00c4ff', '#00b9ff', '#00afff', '#00a5ff', '#009bff', '#0090ff', '#0086ff', '#007cff', '#0071ff', '#0067ff', '#005dff', '#0052ff', '#0048ff', '#003eff', '#0034ff', '#0029ff', '#001fff', '#0015ff', '#000aff', '#0000ff']

If you enjoyed this post and want to buy me a cup of coffee...

The thing is, I'll always accept a cup of coffee. So feel free to buy me one.

Cheers! ☕️