I wanted to sort a list based on the index of the first occurrence of an element.
Example:
l=[3,2,1,2,3,1,4]
output=[3,3,2,2,1,1,4]
I tried the following code.
def sortfunc(idx:int):
return l.index(idx)
print(sorted(l,key=sortfunc))
It working good but when I tried l.sort(key=sortfunc)
Its raising ValueError
.
>>> l=[3,2,1,2,3,1,4]
>>> l.sort(key=sortfunc)
Traceback (most recent call last):
File "<pyshell#63>", line 1, in <module>
l.sort(key=sortfunc)
File "<pyshell#45>", line 2, in sortfunc
return l.index(idx)
ValueError: 3 is not in list
>>>
What am I missing?