list comprehension question

J. Cliff Dyer jcd at sdf.lonestar.org
Tue May 5 13:43:32 EDT 2009


On Fri, 2009-05-01 at 13:00 -0400, John Posner wrote:
> Shane Geiger wrote:
> >    if type(el) == list or type(el) is tuple:
> A tiny improvement:
> 
>         if type(el) in (list, tuple):
> 

Another alternative, which might be useful in some cases:

          if hasattr(el, '__iter__'):

This covers all iterables, not just lists and tuples.  

So:

>>> flatten([1,2, xrange(3,15), 15, 16])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]

The downside, of course, is that some iterables might be infinite (such
as count), which would cause hidden breakage.  But if you have one of
those in your data structure, why are you trying to flatten it anyway?


Cheers,
Cliff





More information about the Python-list mailing list