0

As a new python programmer, I tried to figure how sort function work in the following case:

items = [[1,91],[1,92],[2,93],[2,97],[1,60],[2,77],[1,65],[1,87],[1,100],[2,100],[2,76]]
items.sort(reverse = True)
#After running the above code, I got the following results:
#[[2, 100],[2, 97],[2, 93],[2, 77],[2, 76],[1, 100],[1, 92],[1, 91],[1, 87],[1, 65],[1, 60]]

If I understand correctly, if we don't specify the key in sort function, it means we have two keys, for example, one element such as [2,100] of the items(the full list with list inside of it), and both element[0](2 in this case) and element[1] (100 in this case) are keys, we sort accordingly to the first key element[0] and then sort according to element[1] based on the first sort on element[0], is that right?

Peter Wood
  • 23,859
  • 5
  • 60
  • 99
M00000001
  • 309
  • 2
  • 10
  • 2
    If you don't specify the key, the key is the whole element. So your question is basically how does Python compare lists. It does it element by element. – Barmar Nov 17 '19 at 21:38
  • 1
    https://stackoverflow.com/questions/13052857/comparing-two-lists-using-the-greater-than-or-less-than-operator – Peter Wood Nov 17 '19 at 21:39
  • 1
    https://docs.python.org/3/tutorial/datastructures.html#comparing-sequences-and-other-types – Peter Wood Nov 17 '19 at 21:39

0 Answers0