Reputation: 21
I'm trying to create a program that would order a list by the last character.
["Apple", "Mellon", "Banana"]
This is my list and I need to arrange them such that it becomes.
["Banana", "Apple", "Mellon"]
Upvotes: 2
Views: 4893
Reputation: 2706
You can sort using a function, here we use the lambda function which looks at the last index of the strings inside of your list.
lst = ["Apple", "Mellon", "Banana"]
sorted(lst, key=lambda x: x[-1])
['Banana', 'Apple', 'Mellon']
Without making a copy of the list you can apply the .sort()
. This is a more memory efficient method.
lst.sort(key=lambda x: x[-1])
print(lst)
['Banana', 'Apple', 'Mellon']
Upvotes: 10
Reputation: 48357
You can use sort
method by passing a lambda
expression for key
property.
This method does not return any value but it changes from the original list.
l = ["Apple", "Mellon", "Banana"]
l.sort(key = lambda item: item[-1])
Output
['Banana', 'Apple', 'Mellon']
Upvotes: 1