Q:

How to assign the result of a for loop to a variable in Python

My program generates a random string with a random amount of letters from 10 to 20.
def program():
    import random
    import sys
    x=['q','w','e','r']
    y=random.randint(10,20)
    for t in range (0,y):
       w=random.randint(0,3)
       e=x[w]
       sys.stdout.write(e)

The program will print a random string like 'wwwweewwqqrrrrwwqqeeqqww'. How would I store this string as a variable?

A:

Store it in a variable instead of writing:
e=''

for t in range (0,y):
    w=random.randint(0,3)
    e += x[w]

e is an empty variable and each time you add the value x[w] to it.
I would also recommend using print() over  sys.stdout.write(e) since you do not need additional imports -such as sys, print() is inbuilt.
In this case can I suggest the use of  a tuple for x=['q','w','e','r'] since they are faster.  So: x=('q','w','e','r'1)
but if you are going to need to modify this later then this is not an option available to you (since they are immutable).

A:

You could replace your loop with a list comprehension, and use join():
e = ''.join([random.choice(x) for _ in range(0, y)])

Output:
qwewwwereeeqeqww

