Open In App

Generate Random String Without Duplicates in Python

Last Updated : 28 Nov, 2024
Suggest changes
Share
Like Article
Like
Report

When we need to create a random string in Python, sometimes we want to make sure that the string does not have any duplicate characters. For example, if we're generating a random password or a unique identifier, we might want to ensure each character appears only once.

Using random.sample()

Using random.sample() is the simplest and most efficient function that allows us to pick a specified number of unique elements from a sequence. It ensures there are no duplicates in the result.

Python
import random import string # Generate a random string of 8 unique characters def generate_random_string(length): return ''.join(random.sample(string.ascii_letters, length)) random_string = generate_random_string(8) print(random_string) 

Output
bdxHBher 
  • string.ascii_letters gives us all the letters in the alphabet (both lowercase and uppercase).
  • random.sample() randomly picks length number of unique characters from this list.
  • ''.join() combines the selected characters into a single string.

Using random.shuffle()

Another way to generate a random string without duplicates is to shuffle a list of characters and then select the first few elements. This method gives us more control over the randomization process.

Python
import random import string # Generate a random string of 8 unique characters def generate_random_string(length): chars = list(string.ascii_letters) random.shuffle(chars) # Shuffle the list of characters return ''.join(chars[:length]) random_string = generate_random_string(8) print(random_string) 

Output
qLfzwjxh 

Manually Generating a Random String

If we want to take a more manual approach or need more control over the process, we can create a random string by picking characters one by one while ensuring that each character is unique. This is a bit more complex but useful in some cases.

Python
import random import string # Generate a random string of 8 unique characters def generate_random_string(length): chars = string.ascii_letters result = [] while len(result) < length: char = random.choice(chars) if char not in result: result.append(char) return ''.join(result) random_string = generate_random_string(8) print(random_string) 

Output
rGYZxgbc 
  • While this method works, it is less efficient than the first two because we keep checking for duplicates, which can slow things down as the string length increases.

Similar Reads