On 3/21/07, <b class="gmail_sendername">Keith Dart ♂</b> <<a href="mailto:keith@dartworks.biz">keith@dartworks.biz</a>> wrote:<div><span class="gmail_quote"></span><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Maybe Baypiggies can have a Python snippets night? or a snippets area<br>on the web site.<br><br>Here is one I recently did. Any comments? Improvements?<br><br>def flatten(alist):<br> rv = []<br> for val in alist:<br>
if isinstance(val, list):<br> rv.extend(flatten(val))<br> else:<br> rv.append(val)<br> return rv<br><br><br>This takes a list that may have embedded lists, to any depth, and<br>flattens it to a single list.
</blockquote><div><br></div></div>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:<br><br>
def flatgen(alist):<br> for val in alist:<br> if isinstance(val, list):<br> for val in flatgen(val): yield val<br> else:<br> yield val<br><br>list(flatgen(alist)) is of course equivalent to your function (though probably slower:-).
<br><br>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):<br><br>def flatgeni(alist):
<br> stack = [iter(alist)]<br> while stack:<br> try:<br> val = stack[-1].next()<br> except StopIteration:<br> stack.pop()<br> continue<br> if isinstance(val, list):<br> stack.append(iter(val))
<br> else:<br> yield val<br><br><br><br>Alex<br><br>