Editor

Python Program to Reverse a String Using a Stack

Beginner · Data structures

A stack gives items back in the opposite order to the one they went in (last in, first out), so pushing the characters of a string and then popping them all spells the string backwards. It is a common stack question in school practicals, and it shows clearly why a stack reverses things.

Program

reverse_string_using_stack.py
text = "Python" # or: text = input("Enter a string: ")
stack = []
for ch in text:
stack.append(ch) # push every character
print("Stack after pushing:", stack)
reversed_text = ""
while len(stack) > 0:
reversed_text += stack.pop() # pop the top, the last character pushed
print("Original:", text)
print("Reversed:", reversed_text)
Output
Stack after pushing: ['P', 'y', 't', 'h', 'o', 'n']
Original: Python
Reversed: nohtyP

How it works

  1. The list stack is used as a stack, with the end of the list as the top.
  2. The first loop pushes the characters one by one with append(), so "n", the last character, ends up on top.
  3. The while loop pops characters with pop(), which removes the top one each time, so they come out as n, o, h, t, y, P.
  4. Each popped character is added to reversed_text, and the loop stops when the stack is empty.

Other ways to write it

With push and pop functions

With push and pop functions
def push(stack, item):
stack.append(item)
def pop(stack):
if len(stack) == 0:
return None # underflow: nothing to pop
return stack.pop()
def reverse(text):
stack = []
for ch in text:
push(stack, ch)
result = ""
while len(stack) > 0:
result += pop(stack)
return result
for word in ["stack", "level", ""]:
print(f'"{word}" reversed is "{reverse(word)}"')
Output
"stack" reversed is "kcats"
"level" reversed is "level"
"" reversed is ""

Exam questions usually ask for separate push() and pop() functions like these, and the empty string shows the empty case: nothing is pushed, so nothing is popped and the result is empty too.

Reversing the words of a sentence

Reversing the words of a sentence
sentence = "a stack reverses the order"
stack = []
for word in sentence.split():
stack.append(word) # push each word
reversed_words = []
while stack: # an empty list counts as False
reversed_words.append(stack.pop())
print("Original:", sentence)
print("Reversed:", " ".join(reversed_words))
Output
Original: a stack reverses the order
Reversed: order the reverses stack a

Pushing whole words instead of characters reverses the order of the words while each word stays readable.

Try it yourself

Use the stack to check whether a word is a palindrome, by comparing it with its reverse.

Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.

All Python programs · CBSE class 12 practical file · Python exercises