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.
Sorting a List by the Second Element of the Tuple. If you specifically want to sort a list of tuples by a given element, you can use the sort() method and specify a lambda function as a key. Unfortunately, Python does not allow you to specify the index of the sorting element directly.
Sorting Nested Tuples To sort a tuple, we can use sorted() function. This function sorts by default into ascending order. For example, print(sorted(emp)) will sort the tuple 'emp' in ascending order of the 0th element in the nested tuples, i.e. identificaton number.
To sort a Tuple in Python, use sorted() builtin function. Pass the tuple as argument to sorted() function. The function returns a list with the items of tuple sorted in ascending order.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With