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.

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements