0

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]]
martineau
  • 119,623
  • 25
  • 170
  • 301
Jim
  • 1
  • 6
    `new_lst = sorted(lst, key=lambda x: x[1], reverse=True)` – j1-lee May 29 '22 at 05:08
  • See [**Key Functions**](https://docs.python.org/3/howto/sorting.html#key-functions) section of the documentation's [Sorting HOW TO](https://docs.python.org/3/howto/sorting.html). – martineau May 29 '22 at 08:20

1 Answers1

1

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]]
Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29