Wednesday, September 9, 2009

how to flatten a list of lists in Python

Say we have:

mylist = [ [ 1, 2, 3, 4 ],
[ 'bb', 'uuu', 'bbbb' ] ]


There are different ways of flattening mylist:

  1. The first is the obvious way:

    result = []
    for x in mylist:
    for y in mylist:
    result = result.append( y )


  2. The next one is my preferred way using sum and a list comprehension:

    result = sum( mylist, [] )


  3. The third way is an obfuscation of the previous one

    from itertools import chain
    result_iterator = reduce( chain, mylist )

    Or if you want a list instead of an iterator:

    result = [ x for x in reduce( chain, mylist ) ]



If anyone can think of anything else, I would like to hear about it.

No comments: