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
Stack after pushing: ['P', 'y', 't', 'h', 'o', 'n'] Original: Python Reversed: nohtyP
How it works
- The list
stackis used as a stack, with the end of the list as the top. - The first loop pushes the characters one by one with
append(), so "n", the last character, ends up on top. - The
whileloop pops characters withpop(), which removes the top one each time, so they come out as n, o, h, t, y, P. - 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
"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
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.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises