2

How do I sort a list of lists based on the first element of the lists in Python?

>>> list01 = (['a','b','c'],['b','a','d'],['d','e','c'],['a','f','d'])
>>> map(sorted, list01)
[['a', 'b', 'c'], ['a', 'b', 'd'], ['c', 'd', 'e'], ['a', 'd', 'f']]
>>> sorted(map(sorted, list01))
[['a', 'b', 'c'], ['a', 'b', 'd'], ['a', 'd', 'f'], ['c', 'd', 'e']]
3
  • This looks like it might help you: stackoverflow.com/q/280222/2740086 Commented Mar 6, 2015 at 12:35
  • By default, the sort method sorts in order of index, starting at zero or the first element. Commented Mar 6, 2015 at 12:41
  • If you sort only on the first element, then something like [['a','z','z'],['a','a',b']] will sort to itself (because Python's sort is stable.) Is that what you want? Commented Mar 6, 2015 at 13:14

4 Answers 4

1

Python's sorted() can receive a function to sort by. If you want to sort by the first element in each sublist, you can use the following:

>>> lst = [[2, 3], [1, 2]]
>>> sorted(lst, key=lambda x: x[0])
[[1, 2], [2, 3]]

For more information on sorted(), please see the official docs.

Sign up to request clarification or add additional context in comments.

Comments

1
from operator import itemgetter    
sorted(list01, key=itemgetter(0))

Comments

0
>>> sorted(list01, key=lambda l: l[0])
[['a', 'b', 'c'], ['a', 'f', 'd'], ['b', 'a', 'd'], ['d', 'e', 'c']]

Is this what you mean?

Comments

0

Apart from the passing a key function to the sorted (as show in earlier answers) you can also pass it a cmp (comparison) function in Python2 as follows:

sorted(list01, cmp=lambda b, a: cmp(b[0], a[0]))

Output of above expression would be same as that of using the the key function.

Although they have removed the cmp argument in Python3 from sorted, https://docs.python.org/3.3/library/functions.html#sorted, and using a key function is the only choice.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.