DIGIT-ARC read-only archive · snapshot: July 23, 2026

Sorting a multidimensional list in python

2 posts · originally from https://geek.digit.in/community/threads/sorting-a-multidimensional-list-in-python.124054/

bharat_r
bharat_r Original post #1
Jan 27, 2010 at 8:44 AM
Hello

I have created a multidimensional list in python

I used the following code:

Code:
 r =[(300, 4), (5, 6), (100, 2)]

I tried sorting it in ascending order using r.sort()
and I get [(5, 6), (100, 2), (300, 4)]

I want it to get sorted based on each on the 2nd element instead of the first. That is the result should be [(100,2), (300,4), (5,6)]

How do I go about doing this?

Thank you.
O
Apr 9, 2010 at 12:24 PM
Try this:

from operator import itemgetter
r=[(300,4), (5,6), (100,2)]
s=sorted(r, key=itemgetter(1))
print (s)

The sorted method can be used instead of sort for flexibility. With key attribute you can specify what index element of tuple to use for sorting.

Thanks