Flattening lists

mmanns at gmx.net mmanns at gmx.net
Sat Feb 7 15:39:17 EST 2009


On Sat, 7 Feb 2009 01:06:06 -0800 (PST)
Rhamphoryncus <rhamph at gmail.com> wrote:

> On Feb 6, 10:21 pm, rdmur... at bitdance.com wrote:
> > Quoth Mensanator <mensana... at aol.com>:
> > > def flatten(listOfLists):
> > >     return list(chain.from_iterable(listOfLists))
> >
> >     Python 2.6.1 (r261:67515, Jan  7 2009, 17:09:13)
> >     [GCC 4.3.2] on linux2
> >     Type "help", "copyright", "credits" or "license" for more
> > information. >>> from itertools import chain
> >     >>> list(chain.from_iterable([1, 2, [3, 4]]))
> >     Traceback (most recent call last):
> >       File "<stdin>", line 1, in <module>
> >     TypeError: 'int' object is not iterable
> >     >>> list(chain(*[1, 2, [3, 4]]))
> >     Traceback (most recent call last):
> >       File "<stdin>", line 1, in <module>
> >     TypeError: 'int' object is not iterable
> >     >>> list(chain.from_iterable(['abcd', 'efg', [3, 4]]))
> >     ['a', 'b', 'c', 'd', 'e', 'f', 'g', 3, 4]
> 
> What usecase do you have for such inconsistently structured data?

I have a similar use case in pyspread, which is a Python spreadsheet
that employs numpy object arrays. Since the Python objects in the numpy
arrays are derived from user input, they can be anything, including
nested lists as well as strings, etc.

Since I consider my work-around that treats strings as a special case a
rather ugly hack, I would welcome a robust, generic approach to the
OP's problem.

Martin




More information about the Python-list mailing list