Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,844 questions

55,671 answers

573 users

How to generate a series of unique HEX colors in Python

2 Answers

0 votes
import random

"""
Generate unique HEX colors using randomness in Python.

Notes:
- random.randint(0, 255) gives values in the full RGB range.
- A set ensures uniqueness.
- Produces #RRGGBB strings.
"""

# Convert an integer (0–255) to a two-digit HEX string.
def to_hex(value: int) -> str:
    return f"{value:02x}"

# Generate N unique random HEX colors.
def generate_random_unique_hex_colors(count: int) -> list[str]:
    seen = set()
    colors = []

    while len(colors) < count:
        r = random.randint(0, 255)
        g = random.randint(0, 255)
        b = random.randint(0, 255)

        hex_color = f"#{to_hex(r)}{to_hex(g)}{to_hex(b)}"

        if hex_color not in seen:
            seen.add(hex_color)
            colors.append(hex_color)

    return colors

if __name__ == "__main__":
    n = 12
    colors = generate_random_unique_hex_colors(n)

    print("Generated HEX colors:")
    for c in colors:
        print(c)


"""
run:

Generated HEX colors:
#674669
#659eea
#08d027
#2a52eb
#77784e
#8947de
#a1f9a0
#4fef3f
#8eb473
#c27f51
#42e8db
#d5f7c6

"""

 



answered 17 hours ago by avibootz
0 votes
import random

def generate_random_unique_hex_colors(count: int) -> list[str]:
    colors = set()
    while len(colors) < count:
        r, g, b = (random.randrange(256) for _ in range(3))
        colors.add(f"#{r:02x}{g:02x}{b:02x}")
    return list(colors)

if __name__ == "__main__":
    for c in generate_random_unique_hex_colors(12):
        print(c)


"""
run:

#0e44e6
#adc7a8
#76c266
#96bd17
#9c2044
#39261f
#1e0309
#63e65e
#5b2bd4
#d1dcfb
#ae4f8b
#f182ff

"""

 



answered 17 hours ago by avibootz
...