I'm a little confused about lambda operators in Python right now. The following (working) code sorts a list of tuples after the number of occurrences of a tuples first element over the first elements of all tuples:
tuples = [(2, 1, 8, 4), (3, 4, 8, 1), (3, 8, 1, 4), (4, 1, 8, 3),
(4, 8, 1, 3), (8, 8, 3, 1), (8, 1, 3, 4), (8, 4, 1, 3),
(8, 4, 3, 1)]
temp = list(zip(*tuples))
tuples.sort(key=lambda x: temp[0].count(x[0])
,reverse=True)
print(tuples)
However, if I now try to skip the creating of "temp", i.e write this:
tuples = [(2, 1, 8, 4), (3, 4, 8, 1), (3, 8, 1, 4), (4, 1, 8, 3),
(4, 8, 1, 3), (8, 8, 3, 1), (8, 1, 3, 4), (8, 4, 1, 3),
(8, 4, 3, 1)]
tuples.sort(key=lambda x: list(zip(*tuples))[0].count(x[0])
,reverse=True)
print(tuples)
It throws an error:
Traceback (most recent call last):
File "E:\Python-Programms\Sorting", line 6, in <module>
,reverse=True)
File "E:\Python-Programms\Sorting", line 5, in <lambda>
tuples.sort(key=lambda x: list(zip(*tuples)) [0].count(x[0])
IndexError: list index out of range
Why does this error occur?