-1

I am confused on how lists inside lists get sorted.

L = [[1,1,1],[0,9,0],[2,1,1]]

sorted(L) returns [[0, 9, 0], [1, 1, 1], [2, 1, 1]]

This means that it is not based off sum as 0+9+0 is larger than both of the other ones.

pault
  • 41,343
  • 15
  • 107
  • 149
Richard
  • 23
  • 6
  • 1
    Is the first element's `0, 1, 2` such an illogical order? – Jongware Nov 06 '18 at 17:08
  • 1
    if you want to sort based on the sum, you need to tell it to do so: `sorted(L, key=sum)` – pault Nov 06 '18 at 17:10
  • 1
    Possible duplicate of [How does the key argument in python's sorted function work?](https://stackoverflow.com/questions/32238196/how-does-the-key-argument-in-pythons-sorted-function-work) – pault Nov 06 '18 at 17:11
  • It sorts lexicographically. If the first elements of two sublists are equal, then the second elements are compared, and so on. – timgeb Nov 06 '18 at 17:11

2 Answers2

1

No it is based on all the elements of the iterator starting from the first element of the iterator

sorted(L,key=lambda x:(x[0],x[1],x[2]) #==sorted(L)

In case you need by sum

sorted(L,key=sum) 

A more simplified version of above code to understand the key argument further

print(sorted(L,key=lambda x: x[0]+x[1]+x[2]))
mad_
  • 8,121
  • 2
  • 25
  • 40
0

Built-in sorted considers each element of an iterable in turn. So, for example, [0, 9, 0] appears first because 0 < 1 and 0 < 2.

To help gain intuition, you can test a few examples:

[0,9,0] < [1,1,1]  # True
[0,9,0] < [0,8,0]  # False
[1,1,1] < [2,1,1]  # True

So sorted works consistently with how comparison operators are defined. Sequence objects in Python usually support lexicographic comparison. To sort by the sum of each list, you need to feed a function to the key argument, in this case built-in sum:

res = sorted(L, key=sum)
jpp
  • 159,742
  • 34
  • 281
  • 339