Flattening lists

rdmurray at bitdance.com rdmurray at bitdance.com
Sat Feb 7 00:21:45 EST 2009


Quoth Mensanator <mensanator at aol.com>:
> On Feb 6, 3:23=A0pm, Rhamphoryncus <rha... at gmail.com> wrote:
> > On Feb 5, 1:16=A0pm, Michele Simionato <michele.simion... at gmail.com>
> > wrote:
> >
> > > On Feb 5, 7:24=A0pm, a... at pythoncraft.com (Aahz) wrote:
> > > > In article <a22c77c4-a812-4e42-8972-6f3eedf72... at l33g2000pri.googlegroups.com>,
> > > > Michele Simionato =A0<michele.simion... at gmail.com> wrote:
> > > > >Looks fine to me. In some situations you may also use hasattr(el,
> > > > >'__iter__') instead of isinstance(el, list) (it depends if you want to
> > > > >flatten generic iterables or only lists).
> > > > Of course, once you do that, you need to special-case strings...
> >
> > > Strings are iterable but have no __iter__ method, which is fine in
> > > this context, since I would say 99.9% of times one wants to treat them
> > > as atomic objects, so no need to special case.
> >
> > Don't worry, that little oddity was fixed for you:
> >
> >     Python 3.0+ (unknown, Dec =A08 2008, 14:26:15)
> >     [GCC 4.3.2] on linux2
> >     Type "help", "copyright", "credits" or "license" for more information.
> >     >>>  str.__iter__
> >     <slot wrapper '__iter__' of 'str' objects
> >     >>> bytes.__iter__
> >     <slot wrapper '__iter__' of 'bytes' objects
> >     >>> bytearray.__iter__
> >     <slot wrapper '__iter__' of 'bytearray' objects>
> >
> > I'm in the "why do you need more than 1 depth?" camp. Dispatching
> > based on your own type should be given an extra look. Dispatching
> > based passed in types should be given three extra looks.
> >
> > I didn't realize itertools.chain(*iterable) worked. I guess that
> > needs to be pushed as the canonical form.
> 
> What about this (from the Recipes section of the itertools manual)?
> 
> 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]

--RDM




More information about the Python-list mailing list