Jovid Nurov
Jovid Nurov

Reputation: 31

Creating an array with list of strings

I want to create an array 10*10 (basically 100 elements letter on I can reshape it to 10*10) which has to contain random letter from alphabet.

For example:

array_box = [the first elemet (c), second (e),...100(f)]

Upvotes: 1

Views: 82

Answers (2)

rrkjonnapalli
rrkjonnapalli

Reputation: 437

>>> import random
>>> import string
>>> s = string.letters[:26]
>>> [[random.choice(s) for i in range(10)] for i in range(10)]

Upvotes: 0

Stephen Rauch
Stephen Rauch

Reputation: 49784

That can be done with a couple of comprehensions like:

Code:

letters = [[random.choice('abcdefghijklmnopqrstuvwxyz') 
            for i in range(10)] for j in range(10)]

Test Code:

import random

letters = [[random.choice('abcdefghijklmnopqrstuvwxyz')
            for i in range(10)] for j in range(10)]
print(letters)

Results:

[
    ['g', 'r', 'r', 'g', 'q', 'h', 'n', 'u', 'g', 's'], 
    ['c', 'm', 'g', 'b', 'z', 'g', 'd', 'm', 'x', 'x'], 
    ['r', 'j', 'e', 'c', 'h', 'm', 'q', 'i', 'c', 'm'], 
    ['v', 'w', 'i', 'x', 'x', 'b', 'l', 'f', 'b', 'x'], 
    ['r', 'r', 'c', 'm', 'f', 'g', 'x', 'z', 'b', 'a'], 
    ['j', 's', 'g', 'n', 'q', 'a', 'f', 'v', 'c', 'o'], 
    ['g', 'r', 'o', 'd', 't', 'n', 'b', 'l', 'h', 'z'], 
    ['h', 'p', 'y', 's', 'k', 't', 'u', 'b', 'n', 'q'], 
    ['u', 'b', 'y', 'z', 'q', 't', 'o', 's', 'l', 'c'], 
    ['w', 'e', 'v', 'p', 'o', 'r', 'f', 'm', 'm', 'h']
]

Upvotes: 1

Related Questions