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.
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 The elements are in the given range") else: print("All The elements are not in the given range")
The list is : [32, 12, 42, 61, 58, 60, 19, 16] The result is : All The elements are not in the given range
A list is defined and displayed on the console.
The value for ‘i’ and ‘j’ are defined.
The value for a variable is set to Boolean ‘True’.
The list is iterated over, and the modulus operator is used on each element to check if it is even or odd.
If it is even, the Boolean value is set to ‘False’ and the control breaks out of the loop.
Based on the Boolean value, relevant message is displayed on the console.