"Total flattening" of a tuple

Daniel Yoo dyoo at hkn.eecs.berkeley.edu
Wed Jan 17 20:19:08 EST 2001


Giuseppe Bilotta <oblomov at freemail.it> wrote:
: Hello,

: I'd like to know if it's possible to "totally flatten" a tuple, or
to decompose it

I'm not sure if this is still useful to you, but here's some tuple
flattening code:


###
def flatten(t):
    if type(t) != type(()):
        return (t,)
    elif len(t) == 0:
        return ()
    else:
        return flatten(t[0]) + flatten(t[1:])
###


And here's a small test of it:

###
>>> flatten((1, 2, 3, 4, (5,), (), (), ((6, 7, (8,)))))
(1, 2, 3, 4, 5, 6, 7, 8)
###



More information about the Python-list mailing list