While reading the python documentation I came across the itertools.groupby()
function. It was not very straightforward so I decided to look up some info here on stackoverflow. I found something from How do I use Python's itertools.groupby()?.
There seems to be little info about it here and in the documentation so I decided I to post my observations for comments.
Thanks
To start with, you may read the documentation here.
I will place what I consider to be the most important point first. I hope the reason will become clear after the examples.
ALWAYS SORT ITEMS WITH THE SAME KEY TO BE USED FOR GROUPING SO AS TO AVOID UNEXPECTED RESULTS
itertools.groupby(iterable, key=None or some func)
takes a list of iterables and groups them based on a specified key. The key specifies what action to apply to each individual iterable, the result of which is then used as the heading for each grouping the items; items which end up having same 'key' value will end up in the same group.The return value is an iterable similar to a dictionary in that it is of the form
{key : value}
.Example 1
results in
Example 2
results in
Now for the sorted version
results in
Example 3
results in
Now for the sorted version. I changed the tuples to lists here. Same results either way.
results in