0

How can I sort the following based on the 1st element?

list1 = [["Value313",1],["Value421",3],["Value234",2]]

Ultimately, I should get the following:

list1 = [["Value234",2],["Value313",1],["Value421",3]]
user706838
  • 4,822
  • 12
  • 51
  • 75

3 Answers3

8

The default sort order of lists (lexicographically) is already how you want it.

>>> list1 = [["Value313",1],["Value421",3],["Value234",2]]
>>> list1.sort()
>>> print list1
[['Value234', 2], ['Value313', 1], ['Value421', 3]]
wim
  • 302,178
  • 90
  • 548
  • 690
4
sorted(list1,key=lambda x : x[0])

[['Value234', 2], ['Value313', 1], ['Value421', 3]]

Use sorted and use a key lambda x[0] where x[0] is the first element in each sublist

Or sort in place to avoid creating a new list:

list1 = [["Value313",1],["Value421",3],["Value234",2]]

list.sort(list1,key=lambda x : x[0])
print list1
[['Value234', 2], ['Value313', 1], ['Value421', 3]]
Padraic Cunningham
  • 168,988
  • 22
  • 228
  • 312
4

To sort list1 in place (without creating another list) use:

from operator import itemgetter
list1.sort(key=itemgetter(0))

If you want to create another list and leave list1 unsorted use:

from operator import itemgetter
list2 = sorted(list1, key=itemgetter(0))

You could use a lambda, but operator.itemgetter normally has better performance since it's at C level.

enrico.bacis
  • 29,025
  • 10
  • 83
  • 113
  • Sure I did, for for a list of pair of integers and using `sorted`, the `itemgetter` solution on my (old) machine does *207 µs per loop*, the `lambda` *359 µs per loop* – enrico.bacis Aug 11 '14 at 22:17