Reverse Words in a Given String in Python (original) (raw)

Last Updated : 27 Oct, 2025

Given a string, the task is to reverse the words in it without changing the words themselves. **For example, for "Learning Python is easy", the reversed string would be "easy is Python Learning" (words in reverse order).

Using split() and join()

This method splits the string into words using split(), reverses the list of words and then joins them back into a single string using join().

Python `

s = "Python is fun" res = ' '.join(s.split()[::-1]) print(res)

`

**Explanation:

Using a Loop

This method manually iterates through the list of words in reverse order, building the reversed string step by step. It is helpful when you want to control the process explicitly.

Python `

s = "Python is fun" words = s.split() res = ""

for word in reversed(words): res += word + " "

res = res.strip() print(res)

`

**Explanation:

Using deque from collections

A deque (double-ended queue) is efficient for large strings, as it allows O(1) pops from both ends. This method uses pop() to retrieve words in reverse order.

Python `

from collections import deque s = "Python is fun" words = deque(s.split())

res = "" while words: res += words.pop() + " "

res = res.strip() print(res)

`

**Explanation:

Using Stack

This method uses a stack (LIFO structure) to reverse the order of words. Words are pushed onto the stack and popped to get them in reverse order.

Python `

s = "Python is fun" words = s.split()

stack = [] for word in words: stack.append(word)

res = "" while stack: res += stack.pop() + " "

res = res.strip() print(res)

`

**Explanation: