tags:

views:

671

answers:

2

I'm looking to take a string and create a list of strings that build up the original string.

e.g.:

"asdf" => ["a", "as", "asd", "asdf"]

I'm sure there's a "pythonic" way to do it; I think I'm just losing my mind. What's the best way to get this done?

+12  A: 

One possibility:

>>> st = 'asdf'
>>> [st[:n+1] for n in range(len(st))]
['a', 'as', 'asd', 'asdf']
dF
+1 wow! learn something new everyday :)
Be careful when using this on anything other than very short strings. A 300-character string would generate a 300-element list containing 45,150 characters!
Ben Blank
A minor point, but I would use xrange() instead of range(), since you don't need to create the list of integers:>>> x="asdf">>> [x[:n] for n in xrange(1,len(x)+1)]['a', 'as', 'asd', 'asdf']
+9  A: 

If you're going to be looping over the elements of your "list", you may be better off using a generator rather than list comprehension:

>>> text = "I'm a little teapot."
>>> textgen = (text[:i + 1] for i in xrange(len(text)))
>>> textgen
<generator object <genexpr> at 0x0119BDA0>
>>> for item in textgen:
...     if re.search("t$", item):
...         print item
I'm a lit
I'm a litt
I'm a little t
I'm a little teapot
>>>

This code never creates a list object, nor does it ever (delta garbage collection) create more than one extra string (in addition to text).

Ben Blank
+1, I like the use of an on-the-fly generator.
Evan Fosmark
Note that you get the same benefits much more simply with a simple for loop-- "for n in xrange(len(text)): do_something_with(text[:n+1])"
dF
@dF: That, too. :-)
Ben Blank
Generator is definitely the way to go.
muhuk