[Tutor] flatten a tuple

Remco Gerlich scarblac@pino.selwerd.nl
Wed, 18 Apr 2001 20:11:11 +0200


On  0, Sean 'Shaleh' Perry <shaleh@valinux.com> 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.

In general it's easier to convert tuples to lists for this sort of thing,
then convert them back at the end. That's because it's easier to build
things if they're mutable.

def flatten_reverse_tuple(tuples_tuple):
   result = []
   tuples_list = list(tuples_tuple)
   tuples_list.reverse()
   for tup in tuples_list:
      result.extend(tup)
   return tuple(result)

It doesn't completely flatten it, so that you won't get a big flat tuple if
you have a tuple of tuples of tuples (I love saying that) but you didn't
define what should happen in that case anyway.

-- 
Remco Gerlich