python – How to order a list of lists by the first value

python – How to order a list of lists by the first value

By default, sorted will use the first element:

>>> l1 = [[1,steve],[4,jane],[3,frank],[2,kim]]
>>> sorted(l1)
[[1, steve], [2, kim], [3, frank], [4, jane]]

As noted in the comments, l1.sort() will sort the original list in place, and is a better option if you dont need to preserve the original order.

This is the way the comparison operators work in Python:

>>> [1, something] < [2, something]
True

Note that if the first element compares as equal, it will compare the second element, and so on:

>>> [1, 1, 1] < [1, 1, 2]
True

This means that two names with the same number would be sorted (lexicographically) by the string, not in place:

>>> sorted([[1, mike], [1, bob]])
[[1, bob], [1, mike]]
l1.sort(key=lambda x: int(x[0]))

Should do the trick make sure you have the int() cast as you can run into further errors with larger numbers because the integers are lexicographically compared. i.e., 5 will be larger than 20

python – How to order a list of lists by the first value

Python sort will compare the lists with the first element by default. If theyre the same, it will continue with the second element, and so on.

so

l1.sort()

will do.

But if you really just want to sort by first value and nothing else :

sorted(l1, key=lambda id_and_name: id_and_name[0])
#=> [[1, steve], [2, kim], [3, frank], [4, jane]]

Leave a Reply

Your email address will not be published.