How can I sort a list by matching the words of another list?

Question:

I have two lists of strings like this:

x = ['Apple', 'Banana', 'Coconut']
y = ['Banana', 'Coconut', 'Apple']

How can I sort the Y-list so that it matches the order of the X-list by matching the words to get the following output:

y = ['Apple', 'Banana', 'Coconut']

Can I also make it so that if the Y-list is not equally long as the X-list, it would still sort the content? Like the following example:

x = ['Apple', 'Banana', 'Coconut']
y = ['Coconut', 'Apple']

#Output
y = ['Apple', 'Coconut']

Thanks beforehand.

Asked By: Eliahs Johansson

||

Answers:

Try:

x = ["Apple", "Banana", "Coconut"]
y = ["Coconut", "Apple"]

y.sort(key=x.index)
print(y)

Prints:

['Apple', 'Coconut']

EDIT: The list.index returns zero-based index of first item found in list. So x.index("Coconut") returns 2 and x.index("Apple") returns 0 – so we sort based on that number.

Answered By: Andrej Kesely
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.