# Grouping a list by their last element

Trying to group elements in a list by the their last element. I think this is a good problem to use groupby() from itertools. Here is my solution:

from itertools import groupby

def match_ends(list1):
"""Returns a dictionary of groups of elements whose end elements match
Returns empty dic if given list was empty
Ex: list1 = ["abc", "dbc","aba","baa"]
matched_ends(list1) = { 'c' : ['abc', 'dbc'], 'a' : ['aba', 'baa'] }
"""
matched_ends = {}
list1 = sorted(list1, key = lambda x: x[-1])
for key, group in groupby(list1, lambda x: x[-1]):
matched_ends[key] = list(group)
return matched_ends


Was this a good approach? Am I missing any key points, or any errors I did not forsee that may yield garbage values instead of the program throwing an Error? Is there a quicker way to group elements based on certain criteria that I have yet to see?

# docstring

Your original method is adequately docmented, but you can format your docstring also according to a general style. This SO answer covers some of the templates.

# doctest

If you format your example in the correct way, you can use doctest to test it. This format is also recognised by Sphinx and other documentation tools,

# alternative approach

Another approach would be to use a collections.defaultdict(list)

def match_ends(list1):
result = defaultdict(list)
for item in list1:
result[item[-1]].append(item)
return result


This way you don't have to sort the list first, but need to append to it. If you use python >3.6, the original method will also return a alphabetically sorted dict, while this method will be sorted along the occurrence in the original list.

• I just learned how to use time module and used it between the two functions and I must say yours is much, much faster. I think it's the the sorted() function in my implementation. I'm gunna test it further but thank you for teaching me about proper docstrings! I had no idea there was a format – Anonymous3.1415 Sep 27 '18 at 18:40