Python Program to Reverse Words in String
split(), reversing the list with [::-1], and joining it back with join(), like this: ' '.join(input_string.split()[::-1]).Examples
How to Think About It
Algorithm
Code
def reverse_words(s): words = s.split() reversed_words = words[::-1] return ' '.join(reversed_words) input_string = "Python is fun" print(reverse_words(input_string))
Dry Run
Let's trace the input 'Python is fun' through the code
Split the string
words = ['Python', 'is', 'fun']
Reverse the list
reversed_words = ['fun', 'is', 'Python']
Join reversed words
'fun is Python'
| Step | Words List |
|---|---|
| After split | ['Python', 'is', 'fun'] |
| After reverse | ['fun', 'is', 'Python'] |
| After join | 'fun is Python' |
Why This Works
Step 1: Splitting the string
Using split() breaks the string into words by spaces, making it easier to work with each word separately.
Step 2: Reversing the list
Using [::-1] reverses the order of words in the list, so the last word comes first.
Step 3: Joining words back
Using join() combines the reversed words into a single string with spaces between them.
Alternative Approaches
def reverse_words(s): words = s.split() reversed_words = reversed(words) return ' '.join(reversed_words) print(reverse_words('Python is fun'))
def reverse_words(s): words = s.split() reversed_words = [] for i in range(len(words)-1, -1, -1): reversed_words.append(words[i]) return ' '.join(reversed_words) print(reverse_words('Python is fun'))
Complexity: O(n) time, O(n) space
Time Complexity
Splitting the string and joining words each take O(n) time where n is the length of the string. Reversing the list is also O(n). Overall, the time is O(n).
Space Complexity
Extra space is needed to store the list of words and the reversed list, so space complexity is O(n).
Which Approach is Fastest?
Using slicing [::-1] or reversed() are both efficient and readable. Manual loops are slower and more verbose.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Slicing with [::-1] | O(n) | O(n) | Simple and fast for reversing lists |
| Using reversed() | O(n) | O(n) | Readable and efficient iterator-based reversal |
| Manual loop | O(n) | O(n) | Educational, shows reversal process explicitly |
split() and join() together with slicing to reverse words easily.