[Tutor] flatten

Bill Mill bill.mill at gmail.com
Thu Apr 7 19:03:32 CEST 2005


On Apr 7, 2005 8:00 AM, C Smith <smichr at hotmail.com> wrote:
> After posting the suggestion about splitting a string that contained a
> quoted string, I looked back at my (at least I think it's mine) flatten
> routine and didn't see anything like it at ASPN. Before I would post it
> there, does anyone see any problems with this non-recursive approach?
> 
> I know that there are iterator approaches, but since the list already
> exists is there any problem with flattening the whole thing? Or is part
> of the problem that there may be iterable things that don't need to be
> completely "iterated to completion" before being able to yield the next
> element? (Does that make sense?)
> 
> After searching for "Tim Peters flatten" I was able to find a similar
> routine at
> 
> http://sourceforge.net/project/
> showfiles.php?group_id=87034&package_id=90541&release_id=288585
> 
> (It is in the basictypes folder in the latebind.py script by  Mike C.
> Fletcher.) It's so short, I post it for comparison. I'm not really sure
> why there is a run through all possible indices rather than the ones
> that exist in the given "inlist", though.
> 
<snip code>

1) you should special-case dictionaries:

>>> x = [1, 2, [3, 4, 5, [[6, 7], 8]], 'abc', 9, [10, 11], {'test': 12}]
>>> flatten(x)
>>> x
[1, 2, 3, 4, 5, 6, 7, 8, 'abc', 9, 10, 11, 'test']

2) What's different about your flatten than those ASPN entries? Just
that it flattens in-place? I see a general-purpose flattener and a
flattening generator.

Peace
Bill Mill
bill.mill at gmail.com


More information about the Tutor mailing list