Generating a random string of 6 characters long in Python 3.6.2 I am learning Python, so pardon me if this is the very crude approach.
I am trying to generate a random string using alphanumeric characters.
Following is my code:

#Generating random 6 character string from list 'range'.
def code():
    # List of characters [a-zA-Z0-9]
    chars = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','0','1','2','3','4','5','6','7','8','9']
    code = ''
    for i in range(6):
        n = random.randint(0,61)    # random index to select element.
        code = code + chars[n]      # 6-character string.
    return code


What I am trying to do is pick six random elements from the list of characters and append them.

Is there any better approach?
Simplicity + improvements:


chars list. Instead of hardcoding all lowercase, uppercase and digit chars - string module provides a convenient constants string.ascii_letters and string.digits
random.randint(0,61). Instead of generating random index for further search on chars sequence - random.choice already allows getting a random element from a specified sequence
for ... loop is easily replaced with generator expression




The final version:

import random
import string


def random_alnum(size=6):
    """Generate random 6 character alphanumeric string"""
    # List of characters [a-zA-Z0-9]
    chars = string.ascii_letters + string.digits
    code = ''.join(random.choice(chars) for _ in range(size))
    return code

if __name__ == "__main__":
    print(random_alnum())
    print(random_alnum())
    print(random_alnum())


Sample output:

g7CZ2G
bczX5e
KPS7vt