
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
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.
- Related Articles
- Sort the words in lexicographical order in Java
- Sort the words in lexicographical order in C#
- C++ Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Java Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Swift Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Kotlin Program to Sort Elements in Lexicographical Order (Dictionary Order)
- Haskell Program to Sort Elements in Lexicographical Order (Dictionary Order)
- How to Sort Elements in Lexicographical Order (Dictionary Order) in Golang?
- How to Sort Words in Alphabetic Order using Python?
- Python program to sort out words of the sentence in ascending order
- Last Substring in Lexicographical Order in C++
- Java program to sort words of sentence in ascending order
- K-th Smallest in Lexicographical Order in C++
- Return a sorted array in lexicographical order in JavaScript
- Sort index in ascending order – Python Pandas
