0

I want to sort my list based on the first item such as:

fruits = \
[['Mango', 6, 5, 8.0],
 ['Banana', 2.0, 5, 8.9, 7],
 ['Pineapple', 4, 6.8, 9],
 ['Apple', 3.9, 6, 7, 2]]

to be sorted out like this:

fruits = \
[['Apple', 3.9, 6, 7, 2],
 ['Banana', 2.0, 5, 8.9, 7],
 ['Mango', 6, 5, 8.0],
 ['Pineapple', 4, 6.8, 9]]

I know I have to use sort() function but I don't know how to use it in a right way to produce the outputs that I want.

pradyunsg
  • 18,287
  • 11
  • 43
  • 96
Fynn Mahoney
  • 699
  • 1
  • 7
  • 10

1 Answers1

1

What is your problem exactly? sort() already sorts by the first element.

In [14]: fruits = [["Mango", 6,5,8.0],
         ["Banana", 2.0,5,8.9,7],
         ["Pineapple", 4,6.8,9],
         ["Apple", 3.9,6,7,2]]

In [15]: fruits.sort()

In [16]: fruits
Out[16]: 
[['Apple', 3.9, 6, 7, 2],
 ['Banana', 2.0, 5, 8.9, 7],
 ['Mango', 6, 5, 8.0],
 ['Pineapple', 4, 6.8, 9]]

If your items are classes or variables, you should implement their comparison methods (__ge__, __le__, __gt__, __lt__) accordingly to your sorting needs.

Keep in mind that fruits.sort() modifies the list in place, if you want a new sorted copy, use sorted(fruits)

fortran
  • 74,053
  • 25
  • 135
  • 175