Lambda Sort in Python
Level 3121 keystrokes
This sorts a list of tuples by a specific element using lambda. The key parameter specifies the sorting criterion.
Python code
# A list of (fruit, number) tuples1items = [("apple", 3), ("banana", 1), ("cherry", 2)]# key=lambda x: x[1] sorts by the second element of each tuple# sorted() returns a new list and leaves items unchanged2sorted_items = sorted(items, key=lambda x: x[1])# Prints [('banana', 1), ('cherry', 2), ('apple', 3)]3print(sorted_items)Output
[('banana', 1), ('cherry', 2), ('apple', 3)]Practice typing this code. Results are not recorded in the rankings.
Symbols in this code
The symbols you type in this Python code and how often they appear.
,× 6"× 6(× 5)× 5=× 3_× 2[× 2]× 2:× 1