Sorting lists of lists I. in mission references

i can not how use lamda expression in solve this mission

Screen Link:https://app.dataquest.io/m/1018/lists/19/sorting-lists-of-lists-i

My Code:

def sort_index(some_list):
    some_list.sort(key=lambda x: (x[2], x[0]))

and

print(*grades, sep="\n")

What I expected to happen:
i can not understand what happened in this code.

someone can explain it.how lambda expression work.

and

print(*grades, sep="\n")

*grades what is mean???

4 Likes

Hi @mo7ammedsab,

I’m a newbie to Python, too, so I understand your frustration. This is how I understood the instructions and Dataquest’s code.

According to Python documentation, " Both list.sort() and sorted() have a key parameter to specify a function to be called on each list element prior to making comparisons."

To further illustrate this,

def sortby_grade_then_name(row):              # a function to be called on each list element prior to making comparisons
    return row[2], row[0]                     # row[2] is the **grade** element & row[0] is the **name** element

def sort_index(list_of_lists):
    return list_of_lists.sort(key= sortby_grade_then_name)  

Another way to write the sort_index function is

def sort_index(list_of_lists):
    list_of_lists.sort(key= lambda row: (row[2], row[0])) 

# notice the similarities of the lambda syntax and the sortby_grade_then_name function we defined

For your second question, print(*grades, sep="\n") is just similar to print(grades) but it’s more readable.

print(grades)
Output
[['Alex', 'Male', 'A'], ['Bruno', 'Male', 'A'], ['Casey', 'Male', 'A'], ['François', 'Male', 'A'], ['John', 'Male', 'A'], ['Joshua', 'Male', 'A'], ['Julie', 'Female', 'A'], ['Rebecca', 'Female', 'A'], ['Renny', 'Male', 'A'], ['Adam', 'Male', 'D'], ['Madeeha', 'Female', 'D'], ['Mari', 'Female', 'D'], ['Sue', 'Female', 'D'], ['Dieter', 'Male', 'F'], ['Jelle', 'Male', 'F'], ['Lode', 'Male', 'F'], ['Martijn', 'Male', 'F'], ['Weston', 'Male', 'F']]


print(*grades, sep="\n") # **sep** means separator **"\n"** means line break
Output
['Alex', 'Male', 'A']
['Bruno', 'Male', 'A']
['Casey', 'Male', 'A']
['François', 'Male', 'A']
['John', 'Male', 'A']
['Joshua', 'Male', 'A']
['Julie', 'Female', 'A']
['Rebecca', 'Female', 'A']
['Renny', 'Male', 'A']
['Adam', 'Male', 'D']
['Madeeha', 'Female', 'D']
['Mari', 'Female', 'D']
['Sue', 'Female', 'D']
['Dieter', 'Male', 'F']
['Jelle', 'Male', 'F']
['Lode', 'Male', 'F']
['Martijn', 'Male', 'F']
['Weston', 'Male', 'F']

I hope this explanation helps you.

6 Likes

What a great and thorough reply. This helped a ton. Thank you!

1 Like