Generate a random length is 12 string that is comprised uppercase and lowercase alpha and numbers
Question: How can I create a Python algorithm to generate a 12 character string
comprised of unique uppercase and lowercase alpha and numbers?

In my situation, it would be used as a unique session/key identifier that
would _likely_ be unique over 500K+ generations.

For example:

    
    
    837uNNM9abCb
    
    9HFRHcop24Cd
    

Thanks!


Answer: This is easily achieved using a while loop and Python's `random` and `string`
libraries.

**Code:**

    
    
    import random
    import string
    
    def create():
        _string, counter = "", 0
        while counter < 12:
            choice = random.choice(string.ascii_letters + string.digits)
            if choice not in _string:
                _string += choice
                counter += 1
            else:
                pass
        return _string
    
    print(create())
    

**Output:**

    
    
    YWdTocQs0R4X
    

**What it is doing:**

  1. Creating variables `_string` and `counter`.
  2. Starting a while loop that breaks after the condition `counter < 12` becomes false.(There is a reason for using a `while` loop over a `for` loop here that I will explain later)
  3. Uses Python's random library to find a random number/letter(upper and lowercase).
  4. Checks to see if the choice is a already in the string, if it is not, the choice is added to the string. But if it is, nothing happens and the loop starts over again (Why I used a `while` loop over a `for` loop.
  5. Returns the string!

**Note:** If you are ok with duplicates WITHIN the string this one-liner works
much more efficiently.

    
    
    print(''.join(random.choice(string.letters + string.digits) for _ in range(12)))
    

