Converting a list of lists to a single list

Chris Angelico rosuav at gmail.com
Wed Jul 24 01:40:36 EDT 2013


On Wed, Jul 24, 2013 at 8:34 AM, Rafael Durán Castañeda
<rafadurancastaneda at gmail.com> wrote:
> In [3]: [ y for y in itertools.chain.from_iterable(x)]
> Out[3]: ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2']

Complete aside, given that this has already been pointed out as
solving a different problem: Any time you see a list comp that just
does "[ x for x in foo ]", check to see if it can be replaced by a
simple list constructor:

>>> [ y for y in itertools.chain.from_iterable(x)]
['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2']
>>> list(itertools.chain.from_iterable(x))
['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2']

A bit simpler and achieves the same.

ChrisA



More information about the Python-list mailing list