How to join elements at the beginning and end of the list

Steve D'Aprano steve+python at pearwood.info
Tue Oct 31 13:03:57 EDT 2017


On Wed, 1 Nov 2017 02:29 am, Neil Cerutti wrote:

> You can use the % operator instead of +, and a generator
> expression instead of map. It's a pretty small improvement,
> though.
> 
> values = '||%s||' % ('||'.join(str(s) for s in value_list))
> 
> At least... I THINK you can use that generator expression in 2.7.

Generator expressions are slightly slower when you call join. If join knows
how many items there are, it can allocate space more efficiently, which is
faster.

So even though it takes a bit of time to build, and throw away, a temporary
list, its actually faster to join a list comp than a generator expression.




-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list