How to Compare Two Lists Elementwise for Greater Flags in Python

Compare two equal-length lists element by element and return a list of booleans marking where list_a values are greater than list_b values.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 13 views 0 copies

Python code

17 lines
Python 3.9+
def compare_lists_greater(list_a, list_b):
    """
    Compare two lists elementwise and return a list of booleans
    indicating whether each element in list_a is greater than the
    corresponding element in list_b.
    """
    if len(list_a) != len(list_b):
        raise ValueError("Lists must have the same length")
    return [a > b for a, b in zip(list_a, list_b)]

if __name__ == "__main__":
    list_a = [5, 12, 7, 9]
    list_b = [3, 15, 7, 4]
    result = compare_lists_greater(list_a, list_b)
    print(f"list_a: {list_a}")
    print(f"list_b: {list_b}")
    print(f"Elementwise greater flags: {result}")

Output

stdout
list_a: [5, 12, 7, 9]
list_b: [3, 15, 7, 4]
Elementwise greater flags: [True, False, False, True]

How it works

The function uses zip(list_a, list_b) to pair corresponding elements from both lists into tuples. A list comprehension then evaluates a > b for each pair, producing a boolean for every index. The length check raises ValueError early to avoid silent misalignment when lists differ in size. This approach is memory-efficient because zip returns an iterator rather than building an intermediate list of pairs.

Common mistakes

  • Calling `zip` on lists of different lengths — it silently truncates instead of raising an error
  • Using `>` on non-comparable types like strings vs integers, which raises `TypeError`
  • Forgetting the length guard and getting wrong booleans because pairs are silently dropped

Variations

  1. Use `map(lambda a, b: a > b, list_a, list_b)` and convert to a list for a functional style
  2. Use a `for` loop with `append` if you need to inline extra logic per comparison

Real-world use cases

  • Comparing sensor readings from two time-aligned streams to flag where one exceeded the other.
  • Validating threshold breaches by comparing each batch metric against a baseline list.
  • Generating mask arrays for element-wise filtering in numerical or data-analysis workflows.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.