Python – Test for all Even elements in the List for the given Range

When it is required to test all even elements in the list for the given range, a simple iteration and the modulus operator is used.

Example

Below is a demonstration of the same ?

my_list = [32, 12, 42, 61, 58, 60, 19, 16]

print("The list is :")
print(my_list)

i, j = 2, 7

my_result = True
for index in range(i, j + 1):
    if my_list[index] % 2:
        my_result = False
        break

print("The result is :")

if my_result == True:
    print("All elements in the given range are even")
else:
    print("Not all elements in the given range are even")

Output

The list is :
[32, 12, 42, 61, 58, 60, 19, 16]
The result is :
Not all elements in the given range are even

Explanation

  • A list is defined and displayed on the console.

  • The values for 'i' and 'j' are defined to specify the range (indices 2 to 7).

  • A Boolean variable is initialized to 'True'.

  • The list is iterated over the specified range, and the modulus operator is used on each element to check if it is even or odd.

  • If any element is odd (remainder is non-zero), the Boolean value is set to 'False' and the loop breaks.

  • Based on the Boolean value, a relevant message is displayed on the console.

How It Works

The algorithm checks elements at indices 2 through 7:

  • Index 2: 42 (even) ?

  • Index 3: 61 (odd) ? ? breaks here

Since 61 is odd, the function returns False, indicating not all elements in the range are even.

Alternative Approach Using all()

A more Pythonic way using the built-in all() function ?

my_list = [32, 12, 42, 61, 58, 60, 19, 16]
i, j = 2, 7

# Check if all elements in range are even
result = all(my_list[index] % 2 == 0 for index in range(i, j + 1))

if result:
    print("All elements in the given range are even")
else:
    print("Not all elements in the given range are even")
Not all elements in the given range are even

Conclusion

Use the modulus operator with iteration to check if all elements in a range are even. The all() function provides a more concise alternative for this type of validation.

Updated on: 2026-03-26T01:04:35+05:30

245 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements