python: list comprehension tactics
-
19-08-2019 - |
Question
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?
Solution
One possibility:
>>> st = 'asdf'
>>> [st[:n+1] for n in range(len(st))]
['a', 'as', 'asd', 'asdf']
OTHER TIPS
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
).
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow