This is a bit of a strange bug in Python:
l1 = ['a', 'ab', 'cc', 'bc']
l1.sort(key=lambda x: zip(*l1)[0].count(x[0]))
The intent of this snippet is to sort elements by the frequency of their first letter. However, this produces an error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
IndexError: list index out of range
Computing the keys separately does not give me an error, however:
sortkeys = [zip(*l1)[0].count(x[0]) for x in l1]
Where is this IndexError
coming from? Surely, zip(*l1)[0]
is not empty (it is equal to ('a', 'a', 'c', 'b')
), and x[0]
cannot be empty because all list elements are non-empty...so what's going on?
EDIT: I'm well aware this is not an ideal way to sort a list. I'm curious why this happens, not in what I should write.