"Stringizing" a list

Duncan Booth duncan at rcp.co.uk
Wed Aug 9 11:58:10 EDT 2000


alex at magenta.com (Alex Martelli) wrote in <8mrn4b01r76 at news2.newsguy.com>:

>"Cees de Groot" <cg at gaia.cdg.acriter.nl> wrote in message
>news:8mr91p$g7e$1 at gaia.cdg.acriter.nl...
>> I'm sure I've seen a place with a snippet for this, but I couldn't find
>it:
>>
>> what's the cleanest way to convert a random nested list structure like:
>>
>> ['foo', ['bar', 'baz'], 'quux']
>>
>> into:
>>
>> 'foo bar baz quux' ?
>>
<recursive solution snipped>
>I'm sure there must be something cleverer, but...

You could remove the recursion:

import string

def flatten(aList):
    stack, res = list(aList), []
    stack.reverse()

    while stack:
        val = stack.pop()
        if type(val) == type(''):
            res.append(val)
        else:
            val = list(val)
            val.reverse()
            stack.extend(val)
    return string.join(res)

test = ['foo', ['bar', 'baz'], 'quux']
print flatten(test)

test = ['alpha', ['beta', ('gamma', 'delta'), 'epsilon'], 'omega']
print flatten(test)



More information about the Python-list mailing list