0

I tried with the below code but it seems not to give the intended output.

ran = ''.join(random.choice(string.ascii_uppercase+string.digits) for x in range(10))

So the above code gives '6U1S75' but I want output like

['6U1S75', '4Z4UKK', '9111K4',....]

Please help.

1
  • I edited the code bit because i missed ")". Now it is running but not with the intended outcome. Commented Aug 4, 2022 at 12:36

2 Answers 2

2

I thought this is elegant :

from string import digits, ascii_letters
from random import choices


def rand_list_of_strings(list_size, word_size, pool=ascii_letters + digits):
    return ["".join(choices(pool, k=word_size)) for _ in range(list_size)]

I used ascii_letters instead of ascii_uppercase to have both upper and lower case values, you can edit it to your suiting.

Example use of the above function :

>>> rand_list_of_strings(4, 5)
['wBSbH', 'rJoH8', '9Gx4q', '8Epus']
>>> rand_list_of_strings(4, 10) 
['UWyRglswlN', 'w0Yr7xlU5L', 'p0e6rghGMS', 'Z8zX2Vqyve']
>>>

The first argument is the list size, and the second argument is how large each consequent string should be, and the function invocation returns a list instance. Do not that this should not be used for cryptographic purposes.

Sign up to request clarification or add additional context in comments.

Comments

1

Take a look at this.

list_size = 10
word_size = 4

ran = []

for i in range(list_size):
    rans = ''

    for j in range(word_size):
        rans += random.choice(string.ascii_uppercase + string.digits)

    ran.append(rans)

Though the above solution is clearer and should be preferred, if you absolutely want to do this with list comprehension...

list_size = 10
word_size = 4

ran = [
    ''.join([
        random.choice(string.ascii_uppercase + string.digits) 
        for j in range(word_size)
    ]) 
    for i in range(list_size)
]

2 Comments

Thanks, it works. I did it in a single line with same trick ran = [''.join(random.choice(string.ascii_uppercase+string.digits)for _ in range(4)) for _ in range(10)]
You can use random.choices with k value of word_size instead of choice in a comprehension btw.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.