The task is to write a program that takes a list of words as input and sorts them in alphabetical order. The program should display the sorted list of words, ensuring that the sorting is case-insensitive. To sort words in alphabetical order in Python, we can use the sorted() function or the sort() method, both of which can sort a list of strings in ascending order.
Using sorted() Function
sorted() function returns a new list containing the sorted words, leaving the original list unchanged.
li = ["banana", "apple", "orange", "grape", "kiwi"]
s = sorted(s) # all sorted words
print(s)
Output
['apple', 'banana', 'grape', 'kiwi', 'orange']
Explanation
sorted()Function returns a new list with the elements arranged in ascending order based on lexicographical (alphabetical) order.
Using sort() Method
sort() method sorts the list in place, modifying the original list.
li = ["banana", "apple", "orange", "grape", "kiwi"]
li.sort()
print(li)
Output
['apple', 'banana', 'grape', 'kiwi', 'orange']
Explanation
sort()method sorts the list in place, meaning it modifies the original list and does not return a new list.
Using lambda Function
We can define custom sorting behavior using a lambda function. For example, we can sort words by their lengths and then alphabetically.
li = ["banana", "apple", "orange", "grape", "kiwi"]
s = sorted(li, key=lambda x: (len(x), x))
print(s)
Output
['kiwi', 'apple', 'grape', 'banana', 'orange']
Explanation
- Custom Sorting with
key:key=lambda x: (len(x), x)sorts the list first by the length of the words and then alphabetically if two words have the same length.