How does this Python code work to group a list by the first character of each element?

Question:

We weren’t taught how lambda works, so I was hoping to know how each line works in grouping list elements by each letter. (For example, test_list = [‘an’, ‘a’, ‘geek’, ‘for’, ‘g’, ‘free’], so the output becomes [[‘an’, ‘a’], [‘geek’, ‘g’], [‘for’, ‘free’]]). I’m also confused by the x[0] == y[0] part.

util_func = lambda x, y: x[0] == y[0]
res = []
for sub in test_list:
    ele = next((x for x in res if util_func(sub, x[0])), [])
    if ele == []:
        res.append(ele)
    ele.append(sub)
Asked By: lmrnc587

||

Answers:

The explanation of what lambda is doing in this case has been given in comments. However, it’s worth mentioning that the code shown in the question is extremely cumbersome. A dictionary solves this problem with ease and will almost certainly (I haven’t timed it) be much more efficient:

list_ = ['an', 'a', 'geek', 'for', 'g', 'free']
dict_ = {}

for e in list_:
    dict_.setdefault(e[0], []).append(e)

print(list(dict_.values()))

Output:

[['an', 'a'], ['geek', 'g'], ['for', 'free']]
Answered By: Stuart
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.