Sometimes, we want to generate a random hex color in Python.
In this article, we’ll look at how to generate a random hex color in Python.
How to generate a random hex color in Python?
To generate a random hex color in Python, we can generate random numbers for rgb values.
For instance, we write
import random
r = lambda: random.randint(0,255)
print('#%02X%02X%02X' % (r(),r(),r()))
to call the random.randint
method to generate numbers between 0 and 255.
We call that in a lambda function and we assign the lambda function to r
.
Then we call r
3 times to generate the rgb values.
Conclusion
To generate a random hex color in Python, we can generate random numbers for rgb values.