
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
How to optimize nested if...elif...else in Python?
Here are some of the steps that you can follow to optimize a nested if...elif...else.
1. Ensure that the path that'll be taken most is near the top. This ensures that not multiple conditions are needed to be checked on the most executed path.
2. Similarly, sort the paths by most use and put the conditions accordingly.
3. Use short-circuiting to your advantage. If you have a statement like:
if heavy operation() and light operation():
Then consider changing it to
if lightOperation() and heavy operation():
This will ensure that heavy operation is not even executed if the light operation is false. Same can be done with or conditions as well.
4. Try flattening the nested structure. Though this doesn't optimize code, this can sure help make it more readable.
- Related Articles
- How to use #if..#elif…#else…#endif directives in C#?
- What is the syntax of Python if...elif...else statement?
- Where to put comments in an if...elif..else construct?
- Bash if elif else Statement A Comprehensive Tutorial
- Go Decision Making (if, if-else, Nested-if, if-else-if)
- Explain Nested if-else statement in C language
- How to indent an if...else statement in Python?
- How to indent multiple if...else statements in Python?
- How to use nested if statement in Python?
- How to use if...else statement at the command line in Python?
- What is the ‘if...else if...else’ statement in Java and how to use it?
- How to optimize Python dictionary access code?
- How to optimize Python Dictionary for performance?
- How to optimize Python dictionary memory usage?
- How to use if/else condition in select in MySQL?
