Skip to content

How to Validate List Operations in Python

Learn defensive techniques to prevent IndexError, ValueError, and TypeError when accessing, modifying, or processing lists in Python using LBYL, EAFP, and type validation.

Lists are mutable, dynamic, and central to most Python applications. However, performing operations on lists without proper validation can lead to common runtime errors such as IndexError, ValueError, and TypeError.

This guide explains how to validate list operations using defensive coding techniques, try-except blocks, and type checking.

Method 1: Index Validation (LBYL)

Before accessing an item by index, it is safest to check if the index is within the valid range. This is known as "Look Before You Leap" (LBYL).

def safe_get(lst, index, default=None):
    if -len(lst) <= index < len(lst):
        return lst[index]
    else:
        print(f"Index {index} out of bounds.")
        return default

data = ['a', 'b', 'c']

print(safe_get(data, 1))      # 'b'
print(safe_get(data, 10))     # None (Out of bounds)

Output:

b
Index 10 out of bounds.
None

Method 2: Handling Operations with try-except (EAFP)

Python often favors "Easier to Ask for Forgiveness than Permission" (EAFP). Instead of checking length, just try the operation and catch the error.

Catching IndexError and ValueError

numbers = [10, 20, 30]

try:
    print(numbers[5])
except IndexError:
    print("Error: Index out of range.")

try:
    numbers.remove(99) # Item not in list
except ValueError:
    print("Error: Item not found in list.")

Output:

Error: Index out of range.
Error: Item not found in list.

Method 3: Validating Content Types

Before performing math or string operations on a list, ensure the contents are valid.

def sum_list(lst):
    if not all(isinstance(x, (int, float)) for x in lst):
        raise TypeError("List must contain only numbers.")
    return sum(lst)

data = [1, 2, "three"]

try:
    print(sum_list(data))
except TypeError as e:
    print(f"Validation Error: {e}")

Output:

Validation Error: List must contain only numbers.

Method 4: Validating List Modifications

When modifying lists (e.g., removing items while iterating), standard loops can skip elements or raise errors.

Safe Removal (List Comprehension)

Do not use remove() inside a for loop over the same list. Use a list comprehension to create a new valid list.

data = [1, 2, None, 3, None, 4]


valid_data = [x for x in data if x is not None]

print(f"Cleaned list: {valid_data}")

Output:

Cleaned list: [1, 2, 3, 4]

Conclusion

To validate list operations:

  1. Use LBYL (if index < len(lst)) when you need custom fallback logic for out-of-bounds access.
  2. Use EAFP (try-except IndexError) for standard, Pythonic error handling.
  3. Validate Types (all(isinstance...)) before mathematical operations.
  4. Use List Comprehensions instead of modifying lists during iteration.
Navigation