Flatten Python lists with itertools module
Every now and then you end up with a data structure that looks like this:
listOflists = [[1,2,3],[4,5,6]]
Then you would like to 'flatten' this list to essentially loop over it as a single list instead of a list of 2 separate, smaller lists. Well, check out the itertools module for a good recipe on how to do this.
def flatten(listOfLists): "Flatten one level of nesting" return chain.from_iterable(listOfLists)
Published: 05-31-2012 18:45:00