Python – Test for all Even elements in the List for the given Range
Given a List of elements, test if all elements are even in a range.
Input : test_list = [3, 1, 4, 6, 8, 10, 1, 9], i, j = 2, 5
Output : True
Explanation : 4, 6, 8, 10, all are even elements in range.
Input : test_list = [3, 1, 4, 6, 87, 10, 1, 9], i, j = 2, 5
Output : False
Explanation : All not even in Range.
Method #1: Using loop
In this, we iterate for part of list in the specified range, and flag off the list even if we find anyone odd occurrence in list.
Python3
test_list = [ 3 , 1 , 4 , 6 , 8 , 10 , 1 , 9 ]
print ( "The original list is : " + str (test_list))
i, j = 2 , 5
res = True
for idx in range (i, j + 1 ):
if test_list[idx] % 2 :
res = False
break
print ( "Are all elements even in range : " + str (res))
|
Output
The original list is : [3, 1, 4, 6, 8, 10, 1, 9]
Are all elements even in range : True
Time Complexity: O(n)
Auxiliary Space: O(1)
Method #2: Using all() + list comprehension
In this, all elements to be even are checked using all(), and list comprehension is used to loop over the elements in the range.
Python3
test_list = [ 3 , 1 , 4 , 6 , 8 , 10 , 1 , 9 ]
print ( "The original list is : " + str (test_list))
i, j = 2 , 5
res = all (test_list[idx] % 2 = = 0 for idx in range (i, j + 1 ))
print ( "Are all elements even in range : " + str (res))
|
Output
The original list is : [3, 1, 4, 6, 8, 10, 1, 9]
Are all elements even in range : True
Time Complexity: O(n) where n is the number of elements in the list “test_list”. all() + list comprehension n number of operations.
Auxiliary Space: O(1), no extra space is required
Last Updated :
08 Mar, 2023
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...