Python Forum
Sorting list of names using a lambda (PyBite #5)
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Sorting list of names using a lambda (PyBite #5)
#2
A lambda is a just a function without a name (hence "anonymous"). You can certainly use a named function if it helps you understand it better.

def second_element(s):
    """Return the second element of the string after split()ing"""
    """Will raise IndexError if there are not two elements"""
    return s.split()[1]
    

def sort_by_surname_desc(names):
   return sorted(names, key=second_element, reverse=True)
The benefit of lambda is that if the function is super short, you don't have to define it elsewhere. You can just define it where it's used.
GOTO10 and ndc85430 like this post
Reply


Messages In This Thread
RE: Sorting list of names using a lambda (PyBite #5) - by bowlofred - Oct-16-2020, 03:34 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  List Sorting Problem ZZTurn 5 1,397 Sep-22-2022, 11:23 PM
Last Post: ZZTurn
  Sorting List finndude 9 2,526 Jan-27-2022, 09:37 PM
Last Post: Pedroski55
  sorting a list of lists by an element leapcfm 3 1,924 Sep-10-2021, 03:33 PM
Last Post: leapcfm
  List comprehension and Lambda cametan 2 2,280 Jun-08-2021, 08:29 AM
Last Post: cametan
  Uses cases for list comprehension (encountered while doing PyBite #77) Drone4four 3 2,827 Sep-25-2020, 12:14 PM
Last Post: ndc85430
  Using my REPL to bisect numbers and lists with classes (PyBite #181) Drone4four 2 2,089 Sep-24-2020, 01:47 PM
Last Post: Drone4four
  Counting vowels in a string (PyBite #106) Drone4four 4 2,303 Jul-07-2020, 05:29 AM
Last Post: theknowshares
  list sorting question DPaul 5 2,799 Jun-17-2020, 02:23 PM
Last Post: ndc85430
  Topic: “Filter numbers with a list comprehension” (PyBite #107) Drone4four 4 2,429 Jun-11-2020, 08:31 PM
Last Post: Drone4four
  Conditionals, while loops, continue, break (PyBite 102) Drone4four 2 3,011 Jun-04-2020, 12:08 PM
Last Post: Drone4four

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020