I have this task where I have to create a list that contains random letters. I know you would have to use a 'for' loop to create it but I do not know how to make it contain random letters.
CodePudding user response:
Use the string
module to get a list of letters and the random
module to pick them randomly in a list comprehension:
>>> import string
>>> import random
>>> [random.choice(string.ascii_lowercase) for _ in range(10)]
['r', 'e', 'g', 'p', 'w', 'd', 'x', 'a', 'o', 'd']
CodePudding user response:
You can use something like this that uses the random.choice method and the string.ascii_letters method. This will make it choose randomly between 'a-z' and 'A-Z' and then you just append it to the list.
import random
import string
def listmaker(list, usern):
for x in range(usern):
randLetter = random.choice(string.ascii_letters)
list.append(randLetter)
return(list)