[Baypiggies] Baypiggies snippets

Alex Martelli aleax at google.com
Thu Mar 22 01:32:27 CET 2007

On 3/21/07, Keith Dart ♂ <keith at dartworks.biz> wrote:
> Maybe Baypiggies can have a Python snippets night? or a snippets area
> on the web site.
> Here is one I recently did. Any comments? Improvements?
> def flatten(alist):
>     rv = []
>     for val in alist:
>         if isinstance(val, list):
>             rv.extend(flatten(val))
>         else:
>             rv.append(val)
>     return rv
> This takes a list that may have embedded lists, to any depth, and
> flattens it to a single list.

A generator equivalent can sometimes be more flexible (you might want to
process the leaves one by one rather than building their list in memory,
etc), and is also easily expressed:

def flatgen(alist):
  for val in alist:
    if isinstance(val, list):
        for val in flatgen(val): yield val
        yield val

list(flatgen(alist)) is of course equivalent to your function (though
probably slower:-).

It may be interesting that flatgen makes it easy to eliminate recursion
(maybe interesting if the nesting level can be thousands-deep:-) by keeping
an explicit stack (warning, untested code):

def flatgeni(alist):
  stack = [iter(alist)]
  while stack:
      val = stack[-1].next()
    except StopIteration:
    if isinstance(val, list):
      yield val

-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/baypiggies/attachments/20070321/e7bb4903/attachment.html 

More information about the Baypiggies mailing list