'Insertion sort a nested list without using lambda

[('Bath Spa University', '84%', '37%', '80%', '67%', '29%', '0%'), ('University of Chichester', '80%', '42%', '75%', '0%', '0%', '0%'), ('Canterbury Christ Church University', '76%', '40%', '70%', '0%', '0%', '49%'), ('Buckinghamshire New University', '78%', '39%', '82%', '0%', '0%', '52%'), ('Middlesex University', '82%', '48%', '80%', '57%', '75%', '54%')...

Above is an example of my list of lists. This is the code I have to insertion sort a list.

def insert_sort(lst):
   n = len(lst)
   for i in range(n):
      j = i
      while j > 0 and lst[j-1] > lst[j]:
         tmp = lst[j]
         lst[j] = lst[j-1]
         lst[j-1] = tmp
         j -= 1

I want to have the function sort the nested lists by the first element. Is there a way to do this without using lambda?



Solution 1:[1]

Don't quite understand what you mean 'without lambda', if you don't want to use lambda in key parameter in sort, you can use itemgetter, Rember that don't try to implement your own sort on production, use the build-in sort method, which is fast.

data = [('Bath Spa University', '84%', '37%', '80%', '67%', '29%', '0%'),
        ('University of Chichester', '80%', '42%', '75%', '0%', '0%', '0%'),
        ('Canterbury Christ Church University', '76%', '40%', '70%', '0%', '0%', '49%'),
        ('Buckinghamshire New University', '78%', '39%', '82%', '0%', '0%', '52%'),
        ('Middlesex University', '82%', '48%', '80%', '57%', '75%', '54%')]

from operator import itemgetter

data.sort(key=itemgetter(0))

print(data)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Menglong Li