[Python-ideas] Intermediate Summary: Fast sum() for non-numbers

David Mertz mertz at gnosis.cx
Sun Jul 14 22:57:40 CEST 2013


On Sun, Jul 14, 2013 at 1:42 PM, David Mertz <mertz at gnosis.cx> wrote:

> Another approach in one of the links Sergey gave is nice too, and shorter
> and more elegant than any of his alternatives:
>
>   flat = []
>   map(flat.extend, list_of_lists)
>
> Using map() for a side effect is slightly wrong, but this is short,
> readable, and obvious in purpose.
>

Oh yeah.  That's a Python 2.x thing.  Now map() doesn't actually have
side-effects.  So you'd need to do:

  flat = []
  set(map(flat.extend, list_of_lists))

That starts to border on ugly.  One might also try:

  flat = []
  [flat.extend(l) for l in list_of_lists]

But I'm not thrilled by how that reads either.  Using the chain() versions
is just nicer.  Moreover, if you insist on concrete collections out of it,
you can take your pick (unlike sum().. although you can obviously wrap that
answer in a constructor too):

  flat_tup = tuple(chain(*iter_of_lists))
  flat_set = set(chain(list_of_lists))


-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20130714/cf2a2b30/attachment.html>


More information about the Python-ideas mailing list