GeeksforGeeks App
Open App
Browser
Continue

# Create Random Hex Color Code Using Python

A Hexadecimal color code represents a color code in hexadecimal form. Color codes are the defacto method of representing a color. It helps accurately represent the color, regardless of the display calibration. This article will teach you how to create random hexadecimal color codes in Python

## RGB Color Code

An RGB color code is a tuple containing 3 numbers representing Red, Green, and Blue color values, respectively. Ex. The color code tuple for a 24-bit color system (channel_intensity < 256) would be:

Syntax: (X, Y, Z)

Where,

• X => Red channel intensity
• Y => Green channel intensity
• Z => Blue channel intensity

And the intensity of all channels should be less than 256 (for an 8-bit per channel system).

Hence for pure red color, the color code would be

(255, 0, 0)

Where

• Red  = 255
• Green  = 0
• Blue = 0

Similarly, over 16 million colors could be uniquely represented. Throughout the article, the 8-bit per channel color space would be considered.

## Creating Random Hex Color Codes in Python

Generating a Color code in decimal and then converting it into a Hexadecimal base is the method for achieving the desired result. The process is trivial and could be accomplished easily by using a random value generator such as randint.

### Using randint and format specifiers

randint() is a function inside the random module, allowing the compiler to produce pseudo-random values in a specific range. The syntax of the function is as follows:

Syntax: randint(a, b)

Return random integer in range [a, b], including both end points.

Where a and b are two integers.

The above function will generate a random value in the RGB color space if the range is from 0 to 224. The following example demonstrates the effect produced:

## Python3

 `import` `random` `# Generating a random number in between 0 and 2^24``color ``=` `random.randrange(``0``, ``2``*``*``24``)` `# Converting that number from base-10``# (decimal) to base-16 (hexadecimal)``hex_color ``=` `hex``(color)` `print``(hex_color)`

Output:

`0xd9e906`

#### Explanation:

Firstly a random number is generated in between the range 0 to 224. This is the range for a 24-bit RGB color code. The output of the function is in decimal (base-10) hence it needs to be converted to hexadecimal. For that, the random number is passed to the hex function, which produces the hexadecimal equivalent of the argument to the function. Therefore, the function returns the hexadecimal representation of the number passed to it, and in the end, the hex code is displayed.

Notes: The range 0 to 224 is only for a 24-bit RGB color code. For 8-bit grayscale, the range will be 0 to 28. Hence, the value of the endpoint depends upon the range offered by the color space.

### Requirement for usable hex codes

The hex color codes that are used to represent the color are generally in the following format:

`#(Six_digit_color_code)`

Where the Six_digit_color_code is any 24-bit color code. Hence, the color codes have a pound sign prepended to them. Ex. The color code for a black image would be:

`#000000`

Therefore, to make the program produce hex color codes of the aforementioned structure, the code will be:

## Python3

 `import` `random` `# Generating a random number in between 0 and 2^24``color ``=` `random.randrange(``0``, ``2``*``*``24``)` `# Converting that number from base-10 (decimal) to base-16 (hexadecimal)``hex_color ``=` `hex``(color)` `std_color ``=` `"#"` `+` `hex_color[``2``:]` `print``(std_color)`

Output:

`#d9e906`

#### Explanation:

The code is a modified version of the previous code. The modifications were string slicing to remove the first two characters of the string (“0x”) and to prepend the pound sign (“#”) at the start of the string.

### Using choice function

The secrets module is a part of the standard Python distribution. The module generates cryptographically strong random numbers suitable for managing data such as passwords, account authentication, security tokens, and related secrets. The module contains two functions, namely choice and token_hex

The following code displays how to produce hexadecimal color code using the choice function:

## Python3

 `import` `secrets` `# An empty string that would store the hexadecimal string``s ``=` `""` `# This variable would be used to iterate 6 times``x ``=` `0` `# This loop would iterate 6 times and would produce a random hex string of that length``while` `x < ``6``:` `    ``# Appending a random hexadecimal character to the string``    ``s ``+``=` `secrets.choice(``"0123456789ABCDEF"``)``    ``x ``+``=` `1` `# Displaying the final string``print``(s)`

Output:

`61A33B`

#### Explanation:

Firstly an empty string is initialized that will contain the hexadecimal string. Then a variable is defined that would be used to iterate over a loop. Then a loop is run for 6 iterations (6 characters in a hexadecimal color code) and will produce a random hexadecimal character in each iteration and append that to the empty string. In the end, the string is displayed.

### Using token_hex function:

The following code displays how to produce hexadecimal color code using the token_hex function:

## Python3

 `import` `secrets` `# Calling the token hex function and passing 3 as an argument``# This would produce a 6 characters hexadecimal string``s ``=` `secrets.token_hex(``3``)` `print``(s)`

Output:

`c62e02`

#### Explanation:

This code is the shortest of all the ones described in the article. A call to the token_hex function is made, and the hexadecimal string length is passed as an argument. The reason for passing 3 instead of 6 is that the function takes in argument bytes, where each byte is converted to 2 hexadecimal digits. Hence only 3 needed to be sent as an argument to produce a 6-digit hex string.

#### Using the randomcolor module to generate a random hex color code:

The randomcolor library is a Python library that generates random, aesthetically pleasing colors using the HSV (Hue, Saturation, Value) color space. It can be used to generate a single random color or a list of random colors.

To use the randomcolor library, you will need to install it first using pip. Open a terminal and enter the following command:

`pip install randomcolor`

Once the library is installed, you can import it in your Python code and use it to generate a random color. Here is an example of how to use the randomcolor library to generate a single random color:

## Python3

 `import` `randomcolor` `# Generate a random color``color ``=` `randomcolor.RandomColor().generate()``print``(color)`

You can also use the randomcolor library to generate a random color. To do this, you can use the generate method of the RandomColor class.
Output:

`['#451099']`

My Personal Notes arrow_drop_up