How to Use List Sorting with Custom Key Function

words = ["apple", "banana", "orange", "grape"]
sorted_words = sorted(words, key=lambda x: len(x))
print(f"Original Words: {words}\nSorted Words by Length: {sorted_words}")

Output:

Original Words: [‘apple’, ‘banana’, ‘orange’, ‘grape’]
Sorted Words by Length: [‘apple’, ‘grape’, ‘banana’, ‘orange’]

Leave a Comment

Your email address will not be published.