David
David

Reputation: 265

More efficient for loops in Python (single line?)

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?

Upvotes: 0

Views: 2990

Answers (4)

pradyunsg
pradyunsg

Reputation: 19486

The following will print the same thing as your method.

print ''.join(chr(random.randint(32,126)) for n in range(11))

Upvotes: 0

Brionius
Brionius

Reputation: 14118

You don't need the intermediate step of putting it into a list:

import random
foo=''
for n in range(11):
    foo += chr(random.randint(32,126))
print foo

Upvotes: 0

Inbar Rose
Inbar Rose

Reputation: 43497

You can do it using some functions to make your work more robust.

from random import randint

def random_ascii_string(length=11):
    return ''.join([random_ascii_char() for _ in range(length)])

def random_ascii_char():
    return chr(randint(32,126))

Using it:

>>> random_ascii_string(11)
'.K#d7#q d]%'

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1124758

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&,'

Upvotes: 6

Related Questions