List Validation Techniques
Validation Strategies with all()
1. Type Validation
def validate_number_list(numbers):
return all(isinstance(num, (int, float)) for num in numbers)
## Example usage
valid_list = [1, 2, 3, 4, 5]
invalid_list = [1, 2, '3', 4, 5]
print(validate_number_list(valid_list)) ## True
print(validate_number_list(invalid_list)) ## False
2. Range Validation
def validate_positive_numbers(numbers):
return all(num > 0 for num in numbers)
def validate_number_range(numbers, min_val, max_val):
return all(min_val <= num <= max_val for num in numbers)
## Examples
print(validate_positive_numbers([1, 2, 3, 4])) ## True
print(validate_positive_numbers([1, 2, -3, 4])) ## False
print(validate_number_range([1, 2, 3], 1, 5)) ## True
Comprehensive Validation Techniques
graph TD
A[List Validation] --> B[Type Checking]
A --> C[Range Validation]
A --> D[Condition Validation]
B --> E[Ensure Consistent Types]
C --> F[Check Numeric Boundaries]
D --> G[Apply Custom Conditions]
3. Complex Validation Example
def validate_student_data(students):
## Validate that each student has required fields
required_keys = ['name', 'age', 'grade']
return all(
all(key in student for key in required_keys) and
isinstance(student['name'], str) and
isinstance(student['age'], int) and
0 < student['age'] < 100 and
isinstance(student['grade'], float) and
0 <= student['grade'] <= 100
for student in students
)
## Example usage
valid_students = [
{'name': 'Alice', 'age': 20, 'grade': 85.5},
{'name': 'Bob', 'age': 22, 'grade': 90.0}
]
invalid_students = [
{'name': 'Charlie', 'age': 200, 'grade': 85.5},
{'name': 'David', 'grade': 90.0}
]
print(validate_student_data(valid_students)) ## True
print(validate_student_data(invalid_students)) ## False
Validation Patterns
Validation Type |
Description |
Key Considerations |
Type Validation |
Checks data types |
Use isinstance() |
Range Validation |
Verifies numeric boundaries |
Define min/max limits |
Structural Validation |
Ensures object structure |
Check required keys/attributes |
Best Practices in LabEx Programming
- Use
all()
for comprehensive list validation
- Create modular validation functions
- Handle edge cases carefully
- Provide clear error messages or logging