[Tutor] flatten a tuple

Michael P. Reilly arcege@speakeasy.net
Wed, 18 Apr 2001 14:36:19 -0400 (EDT)


Sean 'Shaleh' Perry wrote
> 
> So I have a tuple:
> 
> ((0, 1, 2), (3,4,5), (6,7,8))
> 
> and I want to get:
> 
> (6,7,8,3,4,5,0,1,2)
> 
> i.e. reverse the container, then get the contents in order.
> 
> The tuple in question happens to be a 3x3, but this need not affect the answer.

How about:

def reverse_flatten(a):
  if not a:
    return ()
  # force to a tuple, just to make sure
  return tuple(a[-1]) + reverse_flatten(a[:-1])

The function will take any sequence and return a tuple.  It will not
completely flatten the given sequence, just the top level.

  -Arcege

-- 
+----------------------------------+-----------------------------------+
| Michael P. Reilly                | arcege@speakeasy.net              |