Avoiding Common Errors
Index Out of Range Errors
Understanding Index Boundaries
fruits = ['apple', 'banana', 'cherry']
## Incorrect access
try:
print(fruits[3]) ## Raises IndexError
except IndexError as e:
print(f"Error: {e}")
## Correct approach
if len(fruits) > 3:
print(fruits[3])
Modifying Lists During Iteration
Potential Pitfalls
## Incorrect iteration and modification
numbers = [1, 2, 3, 4, 5]
for num in numbers:
if num % 2 == 0:
numbers.remove(num) ## Causes unexpected behavior
## Correct approach
numbers = [1, 2, 3, 4, 5]
numbers = [num for num in numbers if num % 2 != 0]
Copying Lists Correctly
Avoiding Unintended References
## Shallow copy (reference)
original = [1, 2, 3]
wrong_copy = original
wrong_copy[0] = 99 ## Modifies original list
## Correct deep copy methods
import copy
## Method 1: Slice copy
correct_copy1 = original[:]
## Method 2: list() constructor
correct_copy2 = list(original)
## Method 3: copy module
correct_copy3 = copy.deepcopy(original)
Common Comparison Mistakes
List Comparison Traps
## Unexpected comparison results
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
print(list1 == list2) ## True
print(list1 is list2) ## False
print(list1 is list3) ## True
Error Handling Strategies
Defensive Programming Techniques
def safe_list_access(lst, index, default=None):
try:
return lst[index]
except IndexError:
return default
## Usage
sample_list = [10, 20, 30]
print(safe_list_access(sample_list, 5, "Not Found"))
List Operation Error Matrix
Error Type |
Cause |
Prevention Strategy |
IndexError |
Accessing non-existent index |
Use len() check |
TypeError |
Incorrect list operations |
Validate input types |
ValueError |
Inappropriate list modifications |
Use try-except blocks |
Visualization of Common Errors
graph TD
A[List Errors] --> B[Index Out of Range]
A --> C[Iteration Modification]
A --> D[Copying References]
A --> E[Comparison Mistakes]
B --> F[Use Boundary Checks]
C --> G[Create New List]
D --> H[Use Deep Copy]
E --> I[Understand == vs is]
Best Practices
- Always validate list indices
- Use list comprehensions for safe modifications
- Understand reference vs. value copying
- Implement error handling mechanisms
LabEx recommends mastering these error prevention techniques to write more robust Python code.