Ad space (banner)
🐍Python Lessons
Lesson 64 / 69

Checking Balanced Parentheses (an application of stacks)

This lesson covers an algorithm that uses a stack to check whether parentheses are balanced, giving you a practical look at using a data structure. It's written for anyone searching "Python check balanced parentheses".

Using a stack (last in, first out), you can check whether parentheses are balanced by pushing an opening bracket like ( or [ onto the stack, and every time a closing bracket appears, checking whether it matches the one on top. The procedure repeats: push on an opening bracket, pop and check for a match on a closing bracket.

The sample code uses a list called stack as the stack, pushing with .append() on an opening bracket, and on a closing bracket, popping with .pop() and checking whether it's a correct match using a dictionary called pairs. In the end, if len(stack) == 0, every bracket was correctly balanced.

A common beginner mistake is handling the case where the type of closing bracket doesn't match. Simply having the same count of opening and closing brackets isn't enough — you also need to verify each pair is the correct type — that's the key insight behind this algorithm.

This is a practical example of using a stack that also applies to checking the syntax of code, or validating a mathematical expression. A similar idea can also power a practical tool for checking that HTML tags are correctly matched.

Python
OUTPUT

💡 The Python engine may take a few seconds to load the first time you run code.

Ad space (banner)
Ad space (in-article)