Acapello
Acapello

Reputation: 127

How to sort list of tuples using both elements of tuple?

I want to sort by first element in tuple, and, if first element for some tuples is equal, by second element. For example, I have [(5,1),(1,2),(1,1),(4,3)] and I want to get [(1,1),(1,2),(4,3),(5,1)]

How can I do it in pythonic way?

Upvotes: 0

Views: 599

Answers (4)

Strik3r
Strik3r

Reputation: 1057

Remember, Sorted method will return a list object. In this case d still remains unsorted.

If you want to sort d you can use

>>>d.sort()

Hope it helps

Upvotes: 0

AKS
AKS

Reputation: 19811

You don't really need to specify the key since you want to sort on the list item itself.

>>> d = [(5,1),(1,2),(1,1),(4,3)]
>>> sorted(d)
[(1, 1), (1, 2), (4, 3), (5, 1)]

Upvotes: 0

Sven Hakvoort
Sven Hakvoort

Reputation: 3621

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

Upvotes: 2

backtrack
backtrack

Reputation: 8144

d = [(5,1),(1,2),(1,1),(4,3)]
print(sorted(d,key=lambda x:(x[0],x[1])))

if you want better performance use itemgetter

Upvotes: 2

Related Questions