Flattening lists

rdmurray at bitdance.com rdmurray at bitdance.com
Sat Feb 7 09:25:02 EST 2009


Rhamphoryncus <rhamph at gmail.com> wrote:
> On Feb 6, 10:21=A0pm, rdmur... at bitdance.com wrote:
> > Quoth Mensanator <mensana... at aol.com>:
> > > def flatten(listOfLists):
> > > =A0 =A0 return list(chain.from_iterable(listOfLists))
> >
> > =A0 =A0 Python 2.6.1 (r261:67515, Jan =A07 2009, 17:09:13)
> > =A0 =A0 [GCC 4.3.2] on linux2
> > =A0 =A0 Type "help", "copyright", "credits" or "license" for more informa=
> tion.
> > =A0 =A0 >>> from itertools import chain
> > =A0 =A0 >>> list(chain.from_iterable([1, 2, [3, 4]]))
> > =A0 =A0 Traceback (most recent call last):
> > =A0 =A0 =A0 File "<stdin>", line 1, in <module>
> > =A0 =A0 TypeError: 'int' object is not iterable
> > =A0 =A0 >>> list(chain(*[1, 2, [3, 4]]))
> > =A0 =A0 Traceback (most recent call last):
> > =A0 =A0 =A0 File "<stdin>", line 1, in <module>
> > =A0 =A0 TypeError: 'int' object is not iterable
> > =A0 =A0 >>> list(chain.from_iterable(['abcd', 'efg', [3, 4]]))
> > =A0 =A0 ['a', 'b', 'c', 'd', 'e', 'f', 'g', 3, 4]
> 
> What usecase do you have for such inconsistently structured data?
> 
> If I'm building a tree I use my own type for the nodes, keeping them
> purely internal, so I can always use isinstance without worrying about
> getting something inconvenient passed in.

I don't have any use cases myself, I'm just pointing out that this
doesn't answer the concerns of the OP, who presumably does.

--RDM




More information about the Python-list mailing list