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]]
1
  • list1.sort() will sort list1 (in place) on the first element as a default Commented Aug 11, 2014 at 16:13

3 Answers 3

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]]
Sign up to request clarification or add additional context in comments.

Comments

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]]

1 Comment

what exactly was the downvote for?
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.

1 Comment

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.