
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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
Lexicographical order is similar way the words are arranged in a dictionary. In this article, we are going to learn how to sort the words in lexicographical order, which means arranging them in alphabetical order (A-Z).
Python provides built-in methods like split() and sorted() to perform this operation.
Using Python split() Method
The Python split() method is used to split a string by using the specified separator. This separator is a delimiter string and can be a comma, a full stop, or any other character to split a string.
Syntax
Following is the syntax of Python str.split() method -
str.split(separator, maxsplit)
Using Python sorted() Function
The Python sorted() function returns the new sorted list from the items in an iterable object. The order of sorting can be set to either ascending or descending order.
Syntax
Following is the syntax of the Python sorted() function -
sorted(iterObject, key, reverse)
Example 1
In this scenario, the split() method is used to break the sentence into a list and the sorted() function is used to sort the list alphabetically. Let's look at the following example, where we are going to sort the words in "welcome to tutorialspoint" in lexicographical order.
str1 = "welcome to tutorialspoint" x = str1.split() result = sorted(x) print(" ", result)
The output of the above program is as follows -
['to', 'tutorialspoint', 'welcome']
Example 2
In this case, we are using both uppercase and lowercase words in the string. We can observe that the uppercase letters come before the lowercase letters as per the ASCII values. For ignoring the case, we can use key=str.lower in the program.
Considering the following example, where we are going to sort the words in "audi Bmw ciaz Aura" and observe how letters case affect order.
str1 = "audi Bmw ciaz Aura" x = str1.split() result = sorted(x) print(" ", result)
The output of the above program is as follows -
['Aura', 'Bmw', 'audi', 'ciaz']
Example 3
Here, we are going to pass the parameter "reverse=True" to change the order from A-Z to Z-A. In the following example, we are going to sort the words in "hi hello vanakam" in reverse alphabetical order.
str1 = "hi hello vanakam" x = str1.split() result = sorted(x, reverse=True) print(" ", result)
The output of the above program is as follows -
['vanakam', 'hi', 'hello']