123

I have a list of tuples that look something like this:

("Person 1",10)
("Person 2",8)
("Person 3",12)
("Person 4",20)

What I want produced, is the list sorted in ascending order, by the second value of the tuple. So L[0] should be ("Person 2", 8) after sorting.

How can I do this? Using Python 3.2.2 If that helps.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
user974703
  • 1,653
  • 4
  • 20
  • 27

3 Answers3

228

You can use the key parameter to list.sort():

my_list.sort(key=lambda x: x[1])

or, slightly faster,

my_list.sort(key=operator.itemgetter(1))

(As with any module, you'll need to import operator to be able to use it.)

Sven Marnach
  • 574,206
  • 118
  • 941
  • 841
  • 3
    I've tried using `L.sort(key=operator.itemgetter(1))` in my code, but I get a NameError, that 'operator' is not defined. Do I need to import anything special? – user974703 Dec 10 '11 at 19:36
  • 3
    Did a bit of a search, need to use `import operator` to use the function. If you add that to your answer I'll mark it accepted. – user974703 Dec 10 '11 at 19:44
  • Testing with timeit.timeit (default options) there's not a huge difference between these two approaches: operator.itemgetter = 1.05µs, lambda = 1.25µs per iteration – Noel Evans Aug 26 '15 at 20:49
  • Thanks for the my_list.sort(key=operator.itemgetter(1)) solution!! :) – aman_novice Jul 20 '16 at 01:41
  • 1
    If you're new to the lambda keyword: http://stackoverflow.com/questions/13669252/what-is-key-lambda – EchoLynx May 01 '17 at 17:23
16

You may also apply the sorted function on your list, which returns a new sorted list. This is just an addition to the answer that Sven Marnach has given above.

# using *sort method*
mylist.sort(key=lambda x: x[1]) 

# using *sorted function*
l = sorted(mylist, key=lambda x: x[1]) 
luizfls
  • 532
  • 6
  • 13
Samuel Nde
  • 2,565
  • 2
  • 23
  • 23
  • This is just the built-in that returns a new list. Your answer doesn't contribute anything to the ones already here, as it is clear that if you wanted a new list you would use `sorted` instead of `list.sort`. – miradulo Aug 05 '18 at 04:30
  • 3
    @SamuelNde I scrolled down here because I wasn't sure if the expression worked the same for sorted so it helped me. – Red Riding Hood Nov 03 '19 at 11:15
  • 1
    Yeah agreed, this helped me too – StackG Sep 05 '20 at 07:23
  • It actually does contribute, you can use `sorted` on sets but `myset.sort` results in an error. So it appears to be the more general answer. – David Waterworth Dec 16 '21 at 23:04
-1
    def findMaxSales(listoftuples):
        newlist = []
        tuple = ()
        for item in listoftuples:
             movie = item[0]
             value = (item[1])
             tuple = value, movie

             newlist += [tuple]
             newlist.sort()
             highest = newlist[-1]
             result = highest[1]
       return result

             movieList = [("Finding Dory", 486), ("Captain America: Civil                      

             War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529), ("The  Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)]
             print(findMaxSales(movieList))

output --> Rogue One

Darrell White
  • 109
  • 1
  • 5
  • A couple of thoughts: This doesn't actually answer the question (how to get a list sorted by a value in the tuple); You could unpack the tuple directly in your loop (for movie, value in listoftuples: ); you've overridden the type 'tuple'; And it can actually be done is a single list comprehension: (return sorted((value, movie) for movie, value in listoftuples)[-1][1]) – RFox Aug 23 '17 at 10:54
  • I appreciate what you're going for, but I would argue that it lacks elegance and could be improved. Generally it would be considered poor practice to transform the order of elements in a tupple like this. I think the points about list comprehension and unpacking tupples would still stand. And I would discourage anyone using this methodology over the accepted answer. – RFox Aug 26 '17 at 19:58
  • I am incapable and could not get the code you posted to work, most likely a user error – Darrell White Sep 05 '17 at 21:20
  • but changed it a bit and no doubt your answer is 200x better. – Darrell White Sep 05 '17 at 21:21
  • def findMaxSales(listoftuples): newlist = sorted((value,movies) for movies, value in listoftuples) return newlist[-1][1] movieList = [("Finding Dory", 486), ("Captain America: Civil War", 408), ("Deadpool", 363), ("Zootopia", 341), ("Rogue One", 529),("The Secret Life of Pets", 368), ("Batman v Superman", 330), ("Sing", 268), ("Suicide Squad", 325), ("The Jungle Book", 364)] print(findMaxSales(movieList)) – Darrell White Sep 05 '17 at 21:21