0

I need to sort a list of tuples in Python by a specific tuple element, let's say it's the second element in this case. I tried

sorted(tupList, key = lambda tup: tup[1])

I have also tried

sorted(tupList, key = itemgetter(1))
'''i imported itemgetter, attrgetter, methodcaller from operator'''

but the list was returned the same both times. I checked

sorting tuples in python with a custom key

sort tuples in lists in python

https://wiki.python.org/moin/HowTo/Sorting

5
  • 7
    Reminder: calling sorted on a list doesn't modify the original list. If you're doing sorted(seq); print(seq);, then you're not going to see any changes. Make sure you're doing new_thing = sorted(seq); print(new_thing) or similar. Commented Apr 15, 2015 at 17:09
  • o_O Your code seems fine to me. Show input and expected output please? Commented Apr 15, 2015 at 17:10
  • 2
    Can you provide an example list that causes the problem? Commented Apr 15, 2015 at 17:11
  • 1
    As is stated by @Kevin, sorted does not mutate a list in place, but returns a new version of it. If you want to mutate in place, you should use tupList.sort(key=lambda t: t[1]) Commented Apr 15, 2015 at 17:14
  • @Kevin you are right. I switched from list.sort() to sorted and forgot I have to save the result somewhere. Please make an answer so I can accept. Commented Apr 15, 2015 at 17:16

1 Answer 1

1

I'm guessing you're calling sorted but not assigning the result anywhere. Something like:

tupList = [(2,16), (4, 42), (3, 23)]
sorted(tupList, key = lambda tup: tup[1])
print(tupList)

sorted creates a new sorted list, rather than modifying the original one. Try:

tupList = [(2,16), (4, 42), (3, 23)]
tupList = sorted(tupList, key = lambda tup: tup[1])
print(tupList)

Or:

tupList = [(2,16), (4, 42), (3, 23)]
tupList.sort(key = lambda tup: tup[1])
print(tupList)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.