- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

# Check for balanced parentheses in Python

Many times we are required to find if an expression is balanced with respect to the brackets present in it. By balanced we mean for each left bracket there is a corresponding right bracket and the sequence of brackets is properly ordered. This has importance in writing a program or a mathematical expression where brackets are heavily used. In this topic, we will see how we can programmatically find out if an expression containing brackets is balanced or not.

## Through Elimination

In this method, we find out the innermost pair of brackets and replace them with null values. We keep doing this till all the pairs of brackets are replaced. If still some bracket is left then the expression is not balanced otherwise the expression is found to be balanced.

## Example

def brackets(expression): all_br = ['()', '{}', '[]'] while any(x in expression for x in all_br): for br in all_br: expression = expression.replace(br, '') return not expression # calling the function input_string = "([]{}()" if brackets(input_string): print(input_string,"balanced") else: print(input_string,"Not balanced")

## Output

Running the above code gives us the following result −

([]{}() Not balanced

- Related Articles
- Check for balanced parentheses in an expression in C++
- Program to check whether parentheses are balanced or not in Python
- Check for balanced parentheses in an expression O(1) space O(N^2) time complexity in Python
- Check for balanced parentheses in an expression - O(1) space - O(N^2) time complexity in C++
- Count pairs of parentheses sequences such that parentheses are balanced in C++
- Program to find maximum number of balanced groups of parentheses in Python
- Print all combinations of balanced parentheses in C++
- Generate Parentheses in Python
- Longest Valid Parentheses in Python
- C++ Program to Check for balanced paranthesis by using Stacks
- Special Syntax with Parentheses in Python
- Check if concatenation of two strings is balanced or not in Python
- How to match parentheses in Python regular expression?
- Minimum Add to Make Parentheses Valid in Python
- Balanced Binary Tree in Python