Saturday 15 October 2016

Why is there no "flatten list" function in python?

The problem
I have a dictionary and each element in the dictionary is a list of codes. I want the set of all unique codes.

Example
codes['1992'] = ['K50', 'K51']
codes['1993'] = ['S72', 'K51']

Approach 
codes.values() gives all codes, but is is a list of lists so it needs to be flattened before I can get the set. It is not difficult, but it always takes me a little time.

Pain poin
Flattening a list of this type is not a major problem, but it is slightly annoying that there is no inbuilt flatten command. Why not? Two possible reasons:
1. It is easy to do (a one-liner) so a special command is not needed.
2. There are corner cases where a flatten command would not work or produce unexpected or non-unique results.

Argument 1 is true, but not sufficient: We often create convenience functions for things that could be done using other functions. Just to make life a little easier. Also, although short and quite easy, it always takes some seconds to think how to deal with nested list comprephensionos (see here for an intuitive example of nested list comprehensions).

Argument 2 is also true, but I wonder if it is avoidable by limiting the flatten function to easy cases only or by including optional parameters that the user can specify. At least other languages have managed this.

I know there are some easy solutions, but often I wish we had flatten function to make life even easier every time I have to do something like this.



More here: http://stackoverflow.com/questions/952914/making-a-flat-list-out-of-list-of-lists-in-python




No comments:

Post a Comment