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

Saturday, November 5, 2022

[FIXED] Why doesn't lambda function accept parameter in bond with sorted()

 November 05, 2022     lambda, python, sorting     No comments   

Issue

Students = (("Squidward", "F", 60),
            ("Sandy", "A", 33),
            ("Patrick","D", 36),
            ("Spongebob","B", 20),
            ("Mr.Krabs","C", 78))

sort_grades = lambda grades: grades[1]

Sorted_Students = sorted(Students,key=sort_grades)

lambda function kinda has a parameter grades. Why don't we pass any parameters in Sorted_Students as a key= so there is no parenthesis after sort_grades. And this code somehow works even without passing any parameters as "grades" so we don't even run the lambda function (how without parameters - imposible). Please detail how this code works the most explicitly, so my dumb brain could get something from your comment


Solution

The key parameter of sorted is a function which will be applied to the elements in order to compare them to each other. Therefore, we only pass the function itself without calling it.

I suggest you read the documentation first next time :) https://docs.python.org/3/library/functions.html#sorted



Answered By - Tomer Ariel
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