Is there a Python module that already does this?

Neal Norwitz neal at metaslash.com
Thu Feb 7 01:45:10 CET 2002


David Eppstein wrote:
> 
> In article <a3rnd1$1a44oq$1 at ID-11957.news.dfncis.de>,
>  "Emile van Sebille" <emile at fenx.com> wrote:
> 
> > def flatten(ary, rslt):
> >     try:
> >         flatten(ary[0], rslt)
> >         flatten(ary[1:], rslt)
> >     except:
> >         if ary: rslt.append(ary)
> >
> > rslt = []
> > flatten(("cat",5,['dog',[3,3,1]],"zoo"), rslt)
> > print 'rslt = ',tuple(rslt)
> 
> Isn't all that list-copying (ary[1:]) going to make for a very inefficient
> algorithm?

This code oughta be faster (adapted from Tim Peter's list flattening code).  
It may be faster to change map() to a list comprehension, ie, 

	''.join([str(x) for x in inlist])

def flatten(inlist, type=type):
    "Side-effect, flattens inlist"
    ltype = types.ListType
    try:
        for ind in xrange(sys.maxint):
            while type(inlist[ind]) is ltype:
                inlist[ind:ind+1] = inlist[ind]
    except IndexError:
        pass
    return ''.join(map(str, inlist))

>>> n = ["cat",5,['dog',[3,3,1]],"zoo"] 
>>> flatten(n)
'cat5dog331zoo'
>>> print n
['cat', 5, 'dog', 3, 3, 1, 'zoo']
>>>

Neal



More information about the Python-list mailing list