- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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.