Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

Can somebody tell me what that one line of code does? Thanks

+4 votes
asked Oct 19, 2022 by Eidnoxon (5,110 points)
Need explanation. I'm coding with python. Can somebody tell me what does the "grade = lambda grades:grade[1]" does? I know the "lambda" function, but i don't really understand.

https://onlinegdb.com/2dWLZcWJH

It sets the variable "grade" to every string within the index 1 in the list full of tuples?

(Sorry for my english)

1 Answer

+2 votes
answered Oct 20, 2022 by Peter Minarik (84,720 points)

It doesn't do anything as the lambda expression in your code is wrong:

grade = lambda grades:grade[1]

The above line says: grade is a (lambda) function that has one argument (grades). What this function does is return the first element of grade. But grade is a function and you cannot index a function, so the expression is faulty.

Your code would make more sense to me like this (feel free to use whatever you find useful in it):

students = [("Bob", "F", 40), ("David", "F", 0)]

firstElement = lambda elements : elements[0]
grade = lambda student : student[1]

print(firstElement(students))           # ("Bob", "F", 40)
print(grade(firstElement(students)))    # F

The first lambda expression is

firstElement = lambda elements : elements[0]

, i.e., from a sequence of elements the first (0th) one is selected. If it makes more sense, you can replace element with student.

The second lambda expression is

grade = lambda student : student[1]

, i.e., from the student object (name, grade, score) we select the grade (the 1st -- zero based -- entry).

You can see in the example that you can combine these: you can select the first student then select the grade of the student:

grade(firstElement(students))
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...