Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to optimize nested if...elif...else in Python?
Nested if...elif...else statements can slow down your program if not structured efficiently. Here are proven techniques to optimize them for better performance and readability.
Put Most Common Conditions First
Place the most frequently executed condition at the top to minimize the number of checks ?
# Less efficient - rare condition checked first
def process_score(score):
if score >= 95: # Only 5% of students
return "Excellent"
elif score >= 85: # 15% of students
return "Good"
elif score >= 70: # 30% of students
return "Average"
else: # 50% of students
return "Below Average"
# More efficient - common condition checked first
def process_score_optimized(score):
if score < 70: # 50% of students - checked first
return "Below Average"
elif score < 85: # 30% of students
return "Average"
elif score < 95: # 15% of students
return "Good"
else: # 5% of students
return "Excellent"
# Test with common case
result = process_score_optimized(65)
print(result)
Below Average
Use Short-Circuit Evaluation
Order conditions from lightest to heaviest operations. Python stops checking once a condition fails ?
import time
def light_operation(x):
return x > 0
def heavy_operation(x):
# Simulate expensive computation
time.sleep(0.1)
return x % 2 == 0
# Inefficient - heavy operation runs first
def check_inefficient(x):
if heavy_operation(x) and light_operation(x):
return "Both conditions met"
return "Conditions not met"
# Efficient - light operation runs first
def check_efficient(x):
if light_operation(x) and heavy_operation(x):
return "Both conditions met"
return "Conditions not met"
# Test with failing light condition
start = time.time()
result = check_efficient(-5) # Light operation fails immediately
end = time.time()
print(f"Result: {result}")
print(f"Time taken: {end - start:.3f} seconds")
Result: Conditions not met Time taken: 0.000 seconds
Flatten Nested Structure
Replace deeply nested conditions with early returns for better readability ?
# Nested structure - harder to read
def validate_user_nested(age, income, credit_score):
if age >= 18:
if income >= 30000:
if credit_score >= 650:
return "Approved"
else:
return "Credit score too low"
else:
return "Income too low"
else:
return "Age requirement not met"
# Flattened structure - early returns
def validate_user_flat(age, income, credit_score):
if age < 18:
return "Age requirement not met"
if income < 30000:
return "Income too low"
if credit_score < 650:
return "Credit score too low"
return "Approved"
# Test both approaches
result1 = validate_user_nested(25, 40000, 700)
result2 = validate_user_flat(25, 40000, 700)
print(f"Nested result: {result1}")
print(f"Flattened result: {result2}")
Nested result: Approved Flattened result: Approved
Use Dictionary Mapping for Multiple Conditions
Replace long if...elif chains with dictionary lookups for better performance ?
# Traditional if...elif approach
def get_day_traditional(day_num):
if day_num == 1:
return "Monday"
elif day_num == 2:
return "Tuesday"
elif day_num == 3:
return "Wednesday"
elif day_num == 4:
return "Thursday"
elif day_num == 5:
return "Friday"
elif day_num == 6:
return "Saturday"
elif day_num == 7:
return "Sunday"
else:
return "Invalid day"
# Dictionary mapping approach
def get_day_optimized(day_num):
days = {
1: "Monday", 2: "Tuesday", 3: "Wednesday",
4: "Thursday", 5: "Friday", 6: "Saturday", 7: "Sunday"
}
return days.get(day_num, "Invalid day")
# Test both approaches
day = get_day_optimized(3)
print(day)
Wednesday
Optimization Summary
| Technique | Best For | Performance Gain |
|---|---|---|
| Most common first | Known frequency patterns | Reduces average checks |
| Short-circuit evaluation | Mixed operation costs | Skips expensive operations |
| Early returns | Deep nesting | Improves readability |
| Dictionary mapping | Many discrete values | O(1) lookup vs O(n) checks |
Conclusion
Optimize nested conditionals by ordering from most common to least common, using short-circuit evaluation for expensive operations, and flattening deeply nested structures with early returns. For many discrete values, consider dictionary mapping for O(1) performance.
