5

I am a python beginner--headbangin'. This is a very basic question and I can't seem to find any straight forward answer, either using google or StackOverFlow.

QUESTION: I have a nested list:

 l = [
 [1,4,3,n]
 [2,2,4,n]
 [3,1,5,n]
 ]

I want to sort the entire list by the second value smallest to largest. I will end up sorting the list again by the third value... and nth value of each nested list.

HOW WOULD ONE SORT based on the SECOND, THIRD, Nth value?

A key is mentioned, but "key=lambda" is often used and that just confuses me more.

EDIT: Thank you guys for your help. I was able to use your advice to solve the problem at hand. I would upvote you but apparently, I can't yet show my thanks in that form. I will return someday and give you your reputation bumps.

2
  • 1
    import operator; l.sort(key=operator.itemgetter(1)) Commented Oct 19, 2015 at 17:02
  • 1
    You may not be able to upvote, but you can accept what you think is the best answer. Commented Oct 23, 2015 at 22:22

2 Answers 2

6

Can also be done using operator

Inside operator.itemgetter(1) you are indicating which index you want to sort on. So, in in this case we are specifying 1 which is the second item.

import operator

l = [[1,4,3], [2,2,4], [3,1,5]]
print(sorted(l, key=operator.itemgetter(1)))

output:

[[3, 1, 5], [2, 2, 4], [1, 4, 3]]
Sign up to request clarification or add additional context in comments.

1 Comment

This even works on multiple nested lists. Thank you for your answer. If you could upvote my question, it will help me reciprocate faster.
5

You can try like this,

>>> l = [[1,4,3], [2,2,4], [3,1,5]]
>>> sorted(l, key=lambda x: x[1])
[[3, 1, 5], [2, 2, 4], [1, 4, 3]]

or:

>>> l.sort(key=lambda x: x[1])
>>> l
[[3, 1, 5], [2, 2, 4], [1, 4, 3]]

1 Comment

stackoverflow.com/questions/13669252/what-is-key-lambda It appears that lambda is on the fly function creator. Which is pretty cool once you understand what is going on. Thank you for your help. Could you please upvote my question so I can reciprocate in the future?

Your Answer

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