I have a list of lists. How do I sort it by the price at index [1]
?
lst = [["Apple", 12], ["Pear", 15], ["Peach", 10]]
new_lst = [["Pear", 15], ["Apple", 12], ["Peach", 10]]
I have a list of lists. How do I sort it by the price at index [1]
?
lst = [["Apple", 12], ["Pear", 15], ["Peach", 10]]
new_lst = [["Pear", 15], ["Apple", 12], ["Peach", 10]]
You can use .sort
to change the original list
. With a key
:
>>> lst.sort(key=lambda x: x[1])
>>> lst
[['Peach', 10], ['Apple', 12], ['Pear', 15]]
>>> lst.sort(key=lambda x: x[1], reverse=True)
>>> lst
[['Pear', 15], ['Apple', 12], ['Peach', 10]]
Note that you need to use reverse=True
to be decending.
Or you can use sorted
to assign the sorted lst
to new_lst
:
>>> new_lst = sorted(lst, key=lambda x: x[1], reverse=True)
>>> new_lst
[['Pear', 15], ['Apple', 12], ['Peach', 10]]