PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, November 3, 2022

[FIXED] How to sort the list based on student's last name using lambda in python?

 November 03, 2022     lambda, list, python, python-2.7, sorting     No comments   

Issue

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


Solution

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.



Answered By - Alfe
Answer Checked By - Mildred Charles (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing