[Tutor] 'Last' in Python?

Mitya Sirenef msirenef at lightbird.net
Mon Mar 11 01:30:48 CET 2013


On 03/10/2013 08:16 PM, Dave Friedman wrote:
> Hi all,
 >
 > I'm teaching myself Python in part with Google's course, and one of 
the exercises is to sort a list of tuples by the last element.
 > e.g.: a list [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields [(2, 2), (1, 
3), (3, 4, 5), (1, 7)].
 >
 > My answer, after figuring out lambda functions, is
 > def sort_last(tuples):
 > return sorted(tuples, key= lambda t: t[-1])
 >
 > Google's answer is much more straightforward, except for one part.
 > def sort_last(tuples)
 > return sorted(tuples, key=last)
 >
 > What is 'last', and where can I find a description of it? Searching 
the web and the python docs hasn't been helpful. (Maybe I'm searching 
badly?)
 > Insight and pointers appreciated.
 >
 > Thanks,
 > -Dave
 >


There is no such python builtin. I would use operator.itemgetter:

from operator import itemgetter

return sorted(tuples, key=itemgetter(-1))


  -m


-- 
Lark's Tongue Guide to Python: http://lightbird.net/larks/

Oaths are the fossils of piety.  George Santayana



More information about the Tutor mailing list