sorting the list by inner elements

ketulp_baroda at ketulp_baroda at
Thu Mar 25 13:59:55 CET 2004

John Hunter <jdhunter at> wrote in message news:<mailman.336.1080136535.742.python-list at>...
> >>>>> "ketulp" == ketulp baroda <ketulp_baroda at> writes:
>     ketulp> Hi, all I want to sort the list,the form of my list is
>     ketulp>   name_city_list=[['jack','new
>     ketulp> york'],['mac','london'],['alice','paris']]
>     ketulp> all inner list has same format i.e first is name and
>     ketulp> second is city.  now I want to sort it by the second
>     ketulp> element of the inner list(by city name).
>     ketulp> i.e after sorting my list should be like this
> The usual way is to simply reverse the tuple, sort, and then reverse
> back
>   tmp = [ (city, name) for name, city in name_city_list]
>   tmp.sort()
>   name_city_list = [ (name, city) for city, name in tmp]
> This is usually faster than writing a custom comparison func for sort.

Hi, John

I like ur idea but this will work for only when inner list has only
two elements. if inner list has five elements and i want to sort the
whole list by 3rd element then how can i do this ?

need ur help,

More information about the Python-list mailing list