Thursday, November 17, 2011

Create an array of identical strings in python

To create an array of identical strings in python (sometimes useful for testing):
In [12]: list("sdfsd" for x in range(1,4))
Out[12]: ['sdfsd', 'sdfsd', 'sdfsd']

Update: a commenter points out a better way. I knew you could do
'a'*5
but didn't think to try this. Thanks!

A shorter version:
In [16]: ["sdfsd"]*5
Out[16]: ['sdfsd', 'sdfsd', 'sdfsd', 'sdfsd', 'sdfsd']

And it's faster too....
$ python -mtimeit -n10000 "list('sdfsd' for i in xrange(1000))"
10000 loops, best of 3: 69.7 usec per loop
$ python -mtimeit -n10000 "['sdfsd']*1000"
10000 loops, best of 3: 5.66 usec per loop

1 comment:

techie said...

A shorter version:
["sdfsd"]*5

And it's faster too....

$ python -mtimeit -n10000 "list('sdfsd' for i in xrange(1000))"
10000 loops, best of 3: 69.7 usec per loop
$ python -mtimeit -n10000 "['sdfsd']*1000"
10000 loops, best of 3: 5.66 usec per loop