1

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?

Ch3steR
  • 20,090
  • 4
  • 28
  • 58
  • `l.sort()` modifies the list in place. While it's running, it may have to remove elements from the list temporarily. – Barmar Jan 20 '20 at 07:43
  • 1
    Try `print(l)` inside `sortfunc`. When you call from `l.sort()` it is empty... – Nick Jan 20 '20 at 07:45
  • This might be because `sorted` operates on a copy of the original list `l`, and `l.sort` operates on the original list itself. Instead, you can create a copy of `l`, then tell the key function to get the index from the copy. – בנימין כהן Jan 20 '20 at 07:45

0 Answers0