python: how to flatten a nested list

Simple nested list of strings

Suppose that you have a simple nested list. Simple in the sense that there is only one level:

data = [['a','b'], ['c'], ['d']]

you can use the operator module and reduce built-in function as follows

import operator
reduce(operator.add, data)
['a', 'b', 'c', 'd']

A more generic version would use list comprehension:

flat_list = [item for sublist in data for item in sublist]

this is equivalent (but faster) shortcut for:

flat_list = []
for sublist in data:
    for item in sublist:
        flat_list.append(item)
Please follow and like us:
This entry was posted in Python and tagged . Bookmark the permalink.

Leave a Reply

Your email address will not be published.