Am I programming in Python mode?

Martin von Loewis loewis at
Wed Feb 2 17:27:41 EST 2000

Justin Sheehy <dworkin at> writes:

> Note the error-checking in there.  If you don't allow duplicates, you
> can't get a string longer than the set of allowed characters.

This gives the starting point to a different approach: If you don't
want duplicates, it is a matter of picking one element after another
from a set, and removing it after it was picked:

import string, random

def randStr(n, lower=1, duplicates=1): 
    if lower: 
        chars = string.lowercase
        chars = string.letters
    chars = list(chars)
    char_list = [None]*n
    for i in range(0,n):
        ch = random.choice(chars)
        char_list[i] = ch
        if not duplicates:
    return string.join(char_list, '')

This also ignores the test for n>len(chars): You'll get an IndexError
if there are no chars left. It is faster if n is close to len(chars),
since it won't retry the same letters over and over again.

Also, since you'll know the length of the resulting string, you can
pre-allocate the list, and only fill the elements.


More information about the Python-list mailing list