0

How would I sort a list of Tuples in Python. For example, I have:

aList = [ ( 'person', 20, 100 ), ( 'cat', 30, 900 ), ( 'dog', 5, 500 ) ]

So I want to sort the Tuples using their third values (100, 900, and 500) I would get:

aList = [ ( 'cat', 30, 900 ), ( 'dog', 5, 500 ), ( 'person', 20, 100 ) ]

When I use the answer from the duplicate question I get the same values back:

data = [ ( 'person', 20, 100 ), ( 'cat', 30, 900 ), ( 'dog', 5, 500 ) ]

def sorted_by_second():
    sorted(data, key=lambda tup: tup[1])
    return data

sorted_by_second()

and I get:

[('person', 20, 100), ('cat', 30, 900), ('dog', 5, 500)]
  • By default `sorted` will sort like that only. `sorted([ ( 'person', 20, 100 ), ( 'cat', 30, 900 ), ( 'dog', 5, 500 ) ])` – thefourtheye Mar 11 '14 at 00:37
  • To your new problem: `sorted()` doesn't modify `data`. You need to either return the result of `sorted()`, or use `data.sort()` and return `data` – mhlester Mar 11 '14 at 01:10

2 Answers2

1

Use the 3rd item as key to sort:

aList.sort(key=lambda x: x[1])
edwardtoday
  • 363
  • 2
  • 14
0

You can use the python sorted method, which can specify a key parameter that is a function which takes an element in the list as an input and returns its value to be sorted by as the output (such as a lambda).

Example:

sorted_list = sorted(aList, key =  lambda x : x[2])
aruisdante
  • 8,875
  • 2
  • 30
  • 37