Sorting Strings by Last Letter

Write a Python lambda function that takes a list of strings and returns a list sorted by the last letter in the string. Return the list.

Example 1:

Input: ['Hello', 'World', 'Python', 'Programming']

Output: ['Programming', 'Hello', 'Python', 'World']

Example 2:

Input: ['Apple', 'Banana', 'Cherry', 'Dates']

Output: ['Banana', 'Apple', 'Dates', 'Cherry']

Use the sorted() function with a lambda function as the key argument.

# Define the lambda function
sort_by_last_letter = lambda words: sorted(words, key=lambda x: x[-1])

# Test the function
print(sort_by_last_letter(['Hello', 'World', 'Python', 'Programming'])) # Output: ['Programming', 'Hello', 'Python', 'World']
print(sort_by_last_letter(['Apple', 'Banana', 'Cherry', 'Dates'])) # Output: ['Banana', 'Apple', 'Dates', 'Cherry']

© Let’s Data Science

LOGIN

Unlock AI & Data Science treasures. Log in!