[Tutor] flatten a tuple

D-Man dsh8290@rit.edu
Fri, 20 Apr 2001 10:41:12 -0400


On Fri, Apr 20, 2001 at 03:14:41PM +0100, alan.gauld@bt.com wrote:
| | Convert the tuples to lists and change the print 
| > | statements to result.append() and you should have 
| > 
| > What you really want is 'extend'
| 
| Nope, I want append. The recursive routine reduces 
| the list to elements before printing thus you never 
| attempt to print a list...

Oh ok.  You have a nested list (only 1 level) , then you strip that
level when you print.  I was trying to get rid of all levels of
nesting, then the print would simply be 'print'.  Same result,
different perspective :-).

| PS Is there a better way of testing the type? 
| For example something that could check for any 
| sequence? if L.hasMethod(__getitems__) or whatever?

It really depends on what you expect to be in the list.  If you want
to allow the list to contain strings, and consider those strings as
"atoms", then that technique won't work.  I think the adapter PEP
or the interfaces PEP (I haven't read the interfaces one yet) might
address this situation, but I don't know that it would consider a
string to be an atom (after all, you can iterate over a string a
character at a time ...).

If you want the code to be slightly faster and use a little less
memory make the following change :

- if  type( L ) == type( [] ) :
+ import types
+ if  type( L ) == types.ListType :

The difference is the first line creates a new list, calls a function
to get its type, then frees the list each time it is executed.  The
second one creates a list, gets its type, frees it only on the import.
OTOH the second form does the same thing for every other type, so it
really depends on where you want the time to be spent.  If you check
the type of other stuff or if you run through the loop a lot it is a
good tradeoff.

-D