"Stringizing" a list

Eric Lorenzo zo at angband.org
Sat Aug 12 16:59:59 EDT 2000


Peter Schneider-Kamp <nowonder at nowonder.de> writes:
> Okay, that works. Still the fastest version (for this
> particular task) seems to be the following:
> 
> def flatten(alist):
>     result=[]
>     for element in alist:
>         if type(element) in (ListType, TupleType):
>             result.extend(flatten(element))
>         else:
>             result.append(element)
>     return result

For a frightening second, I thought that this was a near
character-for-character copy of a piece of code I keep around.  Not
quite, though:

from types import StringType

def flatten(L):
    "Flattens nested sequences into one list"
    result = []
    if type(L) == StringType:
        raise TypeError('Attempt to flatten non-sequence')
    for item in L:
        try:
            result.extend(flatten(item))
        except TypeError:
            result.append(item)
    return result

It uses forgiveness-rather-than-permission exception handling so that
this will flatten anything with the right interface to behave like a
sequence (such as a UserList), not just lists and tuples.  The
exception is strings which, since they are effectively infinitely-deep
nested sequences as Python treats them, would cause infinite recursion
if I didn't check for them explicitly.

Eric



More information about the Python-list mailing list