Well, you can simply zip()
the 2 list and then sort it on the basis of priority
by using sorted()
.
>>> todo = ['see doctor', 'do assignment', 'pay rent', 'check bank account', 'clean room']
>>> priority = [3, 4, 1, 2, 5]
>>> [y for (x,y) in sorted(zip(priority, todo))]
['pay rent', 'check bank account', 'see doctor', 'do assignment', 'clean room']
EDIT: The reason as to why you are getting the error ValueError: 'see doctor' is not in list
is because there is a difference between using list.sort()
and the built-in function sorted()
.
sorted()
returns a new sorted list, leaving the original list unaffected. list.sort()
sorts the list in-place, mutating the list indices.
You can refer this answer for more clarification regarding the difference.
If you refer the source code for list.sort()
(the listsort()
function), you'll notice a comment within the function that says -
The list is temporarily made empty, so that mutations performed by comparison functions can't affect the slice of memory we're sorting.
Hence, when the lambda function executes, it tries to find the index of 'see doctor'
in the list (from todo.index(x)
). But since the list is empty, it returns the ValueError: 'see doctor' is not in list
.
This error is not thrown for sorted()
because it initializes a new empty list and then appends the strings into the newly created list without modify the given list (i.e. todo
).
Source code for list.sort()
and sorted()
.