[Tutor] Composing lists from both items and other lists
Corey Richardson
kb1pkl at aim.com
Wed Feb 2 00:21:15 CET 2011
On 02/01/2011 03:40 PM, John Simon wrote:
> I'm looking for a way to flatten lists inside a list literal, kind of like
> this:
>
>>>> start = '('
>>>> end = ')'
>>>> items = ['abc', '+', 'def']
>>>> [start, *items, end]
> ['(', 'abc', '+', 'def', ')']
>
> Of course, the star doesn't work there. Is there any easy,
> syntactically-lightweight way to get that output?
>
> Thanks,
> John
>
Look into list comprehensions:
http://docs.python.org/tutorial/datastructures.html#list-comprehensions
You could use:
[start, [item for item in items], end]
But then you will have a nested list, which probably doesn't lend itself
to what you want. I myself don't know how to get rid of that, maybe some
of the gurus on this list know how.
More information about the Tutor
mailing list