Let’s say we have a list of fruits: fruits = ["Banana", "Apple", "Orange", "Kiwi", "Jackfruit", "Mulberry"]
and we want to sort the list of fruits alphabetically.
Python provides us with built-in functions to sort them alphabetically. We can use either the sorted()
function or the sort()
method to sort the list.
sorted()
: This returns a new sorted list without modifying the original list.
sort()
: This sorts the list in place, modifying the original list.
sorted()
methodFirst, we'll learn how to use the sorted()
function:
fruits = [ "Banana", "Apple", "Orange", "Kiwi", "Jackfruit", "Mulberry" ]sorted_fruits = sorted(fruits)print("Sorted fruits:", sorted_fruits)
In the code above, we use the sorted()
method of Python, which will create a new list sorted_fruits
containing the sorted version of fruits
without modifying the original list.
sort()
methodNow, we’ll understand another method called the sort()
method:
fruits = [ "Banana", "Apple", "Orange", "Kiwi", "Jackfruit", "Mulberry" ]fruits.sort()print("Sorted fruits:", fruits)
In the above code widget, we are using sort()
, which will sort the list words
in place, modifying the original list.
If the list of words contains mixed case, then we will use the key
parameter of the sort()
or sorted()
function:
fruits = [ "banana", "Apple", "orange", "Kiwi", "jackfruit", "Mulberry" ]sorted_fruits = sorted(fruits, key=str.lower)print("Sorted fruits:", sorted_fruits)
In the above code, we have mixed case words and want case-insensitive sorting. We can use the key
parameter of the sorted()
function or the sort()
method with str.lower
as the key function. This ensures that the sorting is done irrespective of the case. This will sort the words, ignoring the case.
We also have another method to sort mixed case words using lambda
function, let's take a look at the code below:
fruits = [ "banana", "Apple", "orange", "Kiwi", "jackfruit", "Mulberry" ]fruits.sort(key=lambda x: x.lower())print("Sorted fruits:", fruits)
The code above starts with a list of mixed-case words stored in the words
variable. We use the sort()
method on the words
list with a key argument specified as a Lambda function lambda x: x.lower()
. The Lambda function, lambda x: x.lower()
, converts each word to lowercase before sorting. This ensures that the sorting is done in a case-insensitive manner. Finally, the sort()
method sorts the words
list in place, modifying the original list.
Free Resources