Sort the words in lexicographical order in Python


Sorting words in lexicographical order mean that we want to arrange them first by the first letter of the word. Then for the words whose first letter is the same, we arrange them within that group by the second letter and so on just like in a language's dictionary(not the data structure).

Python has 2 functions, sort and sorted for this type of order, let us look at how and when to use each of these methods.

In place sorting: when we want to sort the array/list in place, ie, changing the order in the current structure itself, we can use the sort method directly. For example,

my_arr = [
"hello",
"apple",
"actor",
"people",
"dog"
]

print(my_arr)
my_arr.sort()
print(my_arr)

This will give the output −

['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']

As you can see here, the original array, my_arr has been modified. If you want to keep this array as it is and created a new array when sorting, you can use the sorted method. For example,

Example

 Live Demo

my_arr = [
"hello",
"apple",
"actor",
"people",
"dog"
]

print(my_arr)
# Create a new array using the sorted method
new_arr = sorted(my_arr)

print(new_arr)
# This time, my_arr won't change in place, rather, it'll be sorted
# and a new instance will be assigned to new_arr
print(my_arr)

Output

This will give the output −

['hello', 'apple', 'actor', 'people', 'dog']
['actor', 'apple', 'dog', 'hello', 'people']
['hello', 'apple', 'actor', 'people', 'dog']

As you can see here, the original array did not change.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 20-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements