Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to sort out words of the sentence in ascending order
In order to sort the words of a sentence in ascending order, we first need to split the sentence into words using space as the splitting point. For simplicity, we'll only be splitting on space and let the punctuation be there. We can use replace or regex to remove that as well.
Once we split the sentence, we can sort the words lexicographically (like in a language dictionary) using either sort() or sorted() methods depending on whether we want to sort the array in place or create a new sorted array.
Using sort() Method (In-Place Sorting)
When we want to sort the list in place, changing the order in the current structure itself, we can use the sort() method directly ?
sentence = "mary has a very beautiful dog"
words = sentence.split(" ")
print("Original words:", words)
words.sort()
print("Sorted words:", words)
Original words: ['mary', 'has', 'a', 'very', 'beautiful', 'dog'] Sorted words: ['a', 'beautiful', 'dog', 'has', 'mary', 'very']
As you can see, the original list words has been modified in place.
Using sorted() Method (Creating New List)
If you want to keep the original list unchanged and create a new sorted list, use the sorted() method ?
sentence = "mary has a very beautiful dog"
words = sentence.split(" ")
print("Original words:", words)
# Create a new sorted list
sorted_words = sorted(words)
print("Sorted words:", sorted_words)
# Original list remains unchanged
print("Original words after sorting:", words)
Original words: ['mary', 'has', 'a', 'very', 'beautiful', 'dog'] Sorted words: ['a', 'beautiful', 'dog', 'has', 'mary', 'very'] Original words after sorting: ['mary', 'has', 'a', 'very', 'beautiful', 'dog']
Complete Example with Sentence Reconstruction
Here's a complete example that sorts words and reconstructs the sentence ?
def sort_sentence_words(sentence):
# Split sentence into words
words = sentence.split()
# Sort words alphabetically
sorted_words = sorted(words)
# Join words back into a sentence
sorted_sentence = " ".join(sorted_words)
return sorted_sentence
# Test the function
original = "python programming is very interesting"
sorted_result = sort_sentence_words(original)
print("Original:", original)
print("Sorted:", sorted_result)
Original: python programming is very interesting Sorted: interesting is programming python very
Comparison
| Method | Modifies Original | Returns Value | Best For |
|---|---|---|---|
sort() |
Yes | None | When you don't need the original list |
sorted() |
No | New sorted list | When you need to keep the original |
Conclusion
Use sort() for in-place sorting when you don't need the original order. Use sorted() to create a new sorted list while preserving the original.
