I have a list with student names
students = ["Merol B Joseph", "Ferzil Babu", "Basil Abraham", "Kiran Baby", "Ziya sofia"]
I am trying to sort the list using lambda expression.
I want to sort the list based on student's last name
I just tried like this
student_last_name_alpha_order = students.sort(key=lambda name: name.split(" ")[-1].lower())
then I print student_last_name_alpha_order , but it returns None
That's because sort()
is a method which sorts the list in-place and returns None
.
students = ["Merol B Joseph", "Ferzil Babu", "Basil Abraham", "Kiran Baby", "Ziya sofia"]
students.sort(key=lambda name: name.split(" ")[-1].lower())
print students
Will print:
['Basil Abraham', 'Ferzil Babu', 'Kiran Baby', 'Merol B Joseph', 'Ziya sofia']
You can use sorted()
which is a function returning a sorted version of its input without changing the original:
students = ["Merol B Joseph", "Ferzil Babu", "Basil Abraham", "Kiran Baby", "Ziya sofia"]
x = sorted(students, key=lambda name: name.split(" ")[-1].lower())
print x
print students
prints:
['Basil Abraham', 'Ferzil Babu', 'Kiran Baby', 'Merol B Joseph', 'Ziya sofia']
['Merol B Joseph', 'Ferzil Babu', 'Basil Abraham', 'Kiran Baby', 'Ziya sofia']
But this creates a new list, needs twice the amount of memory and also takes longer because everything needs to be copied. So it's up to you to decide if you really need this. The in-place sorting is more efficient and maybe more error-prone.