Wishlist item: itertools.flatten

Ville Vainio ville at spammers.com
Fri Mar 11 17:44:39 EST 2005


>>>>> "Christos" == TZOTZIOY  <Christos> writes:

    >> For quick-and-dirty stuff, it's often convenient to flatten a sequence
    >> (which perl does, surprise surprise, by default):
    >> 
    >> [1,2,[3,"hello",[[4]]]]  ->
    >> 
    >> [1, 2, 3, 'hello', 4]

    Christos> See Python Library Reference, "5.16.3 Recipes".  Now
    Christos> that all and any (also

The recipe is:

def flatten(listOfLists):
    return list(chain(*listOfLists))

That one is trivial, because it only flattens one level. The
flattening I'm talking about involves flattening to arbitrary depth to
get a single sequence of "atoms". The itertools implementation might
also be able to avoid recursion by using a stack.

    Christos> This is just a personal opinion, but I detest restraints
    Christos> on library (itertools module in this case) expansion
    Christos> when talking about such useful *building blocks*.

Yeah - esp. in the case of flattening. If it was deemed useful enough
to be the default behavior in perl (which is admittedly braindamaged),
it should surely warrant being included as a single function in the
stdlib.

-- 
Ville Vainio   http://tinyurl.com/2prnb



More information about the Python-list mailing list