More efficient for loops in Python (single line?)
Question: I put together this code which generates a string of 11 random printable ascii
characters:

    
    
    import random
    foo=[]
    for n in range(11):
        foo.append(chr(random.randint(32,126)))
    print "".join(foo)
    

It works fine, but I can't help feel that there might be a more efficient way
than calling "append" 11 times. Any tips in making it more Pythonic?


Answer: Use a list comprehension:

    
    
    foo = [chr(random.randint(32,126)) for _ in xrange(11)]
    

You can combine that with the `str.join()`:

    
    
    print ''.join([chr(random.randint(32,126)) for _ in xrange(11)])
    

I've used `xrange()` here since you don't need the list produced by `range()`;
only the sequence.

Quick demo:

    
    
    >>> import random
    >>> ''.join([chr(random.randint(32,126)) for _ in xrange(11)])
    'D}H]qxfD6&,'
    

