stererarna stererarna - 1 month ago 13
Python Question

How to order a list of lists by the first value

I have a list of lists that looks like this

l1 = [[1,'steve'],[4,'jane'],[3,'frank'],[2,'kim']]

and I want to order them by the first number

how would i go about this, thank you

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'