1. def validate_lists(lists, expected_length):
  2. """
  3. Validates a list of lists to ensure they all have the expected length.
  4. Handles failures gracefully without async logic.
  5. Args:
  6. lists: A list of lists to validate.
  7. expected_length: The expected length of each inner list.
  8. Returns:
  9. A list of validation errors. Empty list if all lists are valid.
  10. """
  11. errors = []
  12. for i, lst in enumerate(lists):
  13. if not isinstance(lst, list):
  14. errors.append(f"Error: Element at index {i} is not a list.")
  15. continue
  16. if len(lst) != expected_length:
  17. errors.append(f"Error: List at index {i} has length {len(lst)}, expected {expected_length}.")
  18. return errors
  19. if __name__ == '__main__':
  20. # Example usage
  21. list1 = [1, 2, 3]
  22. list2 = [4, 5, 6]
  23. list3 = [7, 8]
  24. lists = [list1, list2, list3]
  25. expected_length = 3
  26. errors = validate_lists(lists, expected_length)
  27. if errors:
  28. print("Validation Errors:")
  29. for error in errors:
  30. print(error)
  31. else:
  32. print("All lists are valid.")
  33. #Example with invalid type
  34. lists = [list1, "not a list", list2]
  35. expected_length = 3
  36. errors = validate_lists(lists, expected_length)
  37. if errors:
  38. print("Validation Errors:")
  39. for error in errors:
  40. print(error)
  41. else:
  42. print("All lists are valid.")

Add your comment