Open In App

Python – Get Indices of Even Elements from list

Improve
Improve
Like Article
Like
Save
Share
Report

Sometimes, while working with Python lists, we can have a problem in which we wish to find Even elements. This task can occur in many domains such as web development and while working with Databases. We might sometimes, require to just find the indices of them. Let us discuss certain ways to find indices of Even elements. 

Method #1: Using loop This is a brute force method in which this task can be performed. In this, we check for even elements in the list and append its index accordingly. 

Python3




# Python3 code to demonstrate working of
# Even Elements indices
# using loop
 
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Even Elements indices
# using loop
res = []
for idx, ele in enumerate(test_list):
    if ele % 2 == 0:
        res.append(idx)
 
# printing result
print("Indices list Even elements is : " + str(res))


Output

The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Even elements is : [1, 2, 3]

Time complexity: O(n), where n is the length of the input list. 
Auxiliary space: O(k), where k is the number of even elements in the input list.

Method #2: Using list comprehension This is the shorthand by which this task can be performed. This method works in a similar way as the above method. The difference is that it’s a one-liner. 

Python3




# Python3 code to demonstrate working of
# Even Elements indices
# using list comprehension
 
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Even Elements indices
# using list comprehension
res = [idx for idx, ele in enumerate(test_list) if ele % 2 == 0]
 
# printing result
print("Indices list Even elements is : " + str(res))


Output

The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Even elements is : [1, 2, 3]

Time complexity: O(n), where n is the length of the input list.

Auxiliary space complexity: O(k), where k is the number of even elements in the input list.

Method #3: Using the filter method This is the shorthand by which this task can be performed. This method works in a similar way as the above method. The difference is that it uses an index list to get the index of elements. 

Python




# Python3 code to demonstrate working of
# Even Elements indices
# using filter method
 
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Even Elements indices
# using filter method
res = filter(lambda i : test_list[i]%2==0 , range(len(test_list)))
         
# printing result
print("Indices list Even elements is : " , res)


Output

The original list is : [5, 6, 10, 4, 7, 1, 19]
('Indices list Even elements is : ', [1, 2, 3])

The time complexity  is O(n), where n is the length of the input list. 

The auxiliary space  is O(1), since it does not use any additional data structure to store the input list or the filtered result.

Method#4: Using recursion and bitwise & operator

Python3




# Python3 code to demonstrate working of
# Even Elements indices
# using recursion
def FindEvenIndices(lst,res,i):
  if i == len(lst):return res
  if lst[i]&1 != 0:
    pass
  else:
    res.append(i)
  return FindEvenIndices(lst,res,i+1)
     
 
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# Even Elements indices
# using loop
res = []
 
# printing result
print("Indices list Even elements is : " + str(FindEvenIndices(test_list,res,0)))
 
#This code is contributed by Vinay Pinjala.


Output

The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Even elements is : [1, 2, 3]

Time Complexity : O(n)
Auxiliary Space: O(n)

Method #5: Using numpy library

Note: Install numpy module using command “pip install numpy”

Python3




#importing numpy library
import numpy as np
 
#initializing list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
#printing original list
print("The original list is : " + str(test_list))
 
#using numpy to find even indices
res = np.where(np.array(test_list) % 2 == 0)[0]
 
#printing result
print("Indices list Even elements is : " + str(res))
#This code is contributed by Edula Vinay Kumar Reddy


Output:

The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices list Even elements is : [1 2 3]

Time Complexity: O(n)
Auxiliary Space : O(n)

Method #6: Using reduce():

Algorithm:

1.Import the reduce function from the functools library.
2.Define the input list test_list.
3.Apply the reduce function to the list using a lambda function.
4.The lambda function checks if the value of the current tuple is even. If so, it adds the index of the tuple to the result list. Otherwise, it ignores the 5.current value and returns the current result list.
6.The initial value of the result list is an empty list.
7.Print the resulting list of indices.

Python3




from functools import reduce
 
# input list
test_list = [5, 6, 10, 4, 7, 1, 19]
#printing original list
print("The original list is : " + str(test_list))
  
 
# apply reduce function to list
# lambda function checks if the value of the current tuple is even
# if so, it adds the index of the tuple to the result list
# otherwise, it ignores the current value and returns the current result list
# initial value of result list is an empty list
res = reduce(lambda x, y: x + [y[0]] if y[1] % 2 == 0 else x, enumerate(test_list), [])
 
# print the resulting list of indices
print(res)
#This code is contributed by Jyothi pinjala.


Output

The original list is : [5, 6, 10, 4, 7, 1, 19]
[1, 2, 3]

Time Complexity: O(n), where n is the length of the input list. This is because the reduce function needs to iterate through the entire list once.
Auxiliary Space: O(n), where n is the length of the input list. This is because the reduce function creates a new list to store the result, which has a size proportional to the number of even values in the input list.

Method #7: Using a list comprehension and the index method: 

Algorithm:

1.Initialize an empty list called ‘res’ to store the indices of even elements.
2.Iterate over each element ‘x’ in the input list ‘test_list’.
3.Check if ‘x’ is even using the modulus operator. If it is, find its index in the input list using the ‘index’ method and append it to ‘res’.
4.Return the final list ‘res’ containing the indices of even elements.
5.Print the final list.

Python3




# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
 
# using the index method
# to find the indices of even elements
res = []
for x in test_list:
    # check if the element is even
    if x % 2 == 0:
        # if it is, add its index to the result list
        res.append(test_list.index(x))
 
# printing result
print("Indices of even elements: " + str(res))
#This code is contributed by Jyothi pinjala.


Output

The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices of even elements: [1, 2, 3]

Time complexity:

The ‘for’ loop iterates over each element in the input list, which takes O(n) time where n is the length of the input list.
The ‘index’ method takes O(n) time in the worst case to find the index of an element in a list.
Therefore, the time complexity of this algorithm is O(n^2).

Space complexity:

The only additional space used in this algorithm is the list ‘res’ which can contain at most n elements (all even elements in the input list).
Therefore, the space complexity of this algorithm is O(n).

Method #8: Using pandas library.

Algorithm:

  1. Convert the input list to a pandas Series.
  2. Filter the series to select the elements that are even using a boolean mask created using the modulo operator.
  3. Extract the index of the selected elements using the index attribute of the series.
  4. Convert the resulting pandas Index object to a list using the tolist() method.
  5. Output the resulting list of indices.

Python3




import pandas as pd
# initialize list
test_list = [5, 6, 10, 4, 7, 1, 19]
 
# printing original list
print("The original list is : " + str(test_list))
df = pd.Series(test_list)
res = df[df % 2 == 0].index.tolist()
# printing result
print("Indices of even elements: " + str(res))


Output

The original list is : [5, 6, 10, 4, 7, 1, 19]
Indices of even elements: [1, 2, 3]

Time complexity:

Iterating over the input list takes O(n) time, where n is the length of the list.
Checking whether each element is even using the modulo operator takes constant time.
Appending the index of even elements to the output list takes constant time.
Therefore, the overall time complexity of this method is O(n), where n is the length of the input list.
Space complexity:

Creating an empty list to store the indices of even elements takes constant space.
Appending the index of each even element to the output list takes O(k) space, where k is the number of even elements in the input list.
Therefore, the overall space complexity of this method is O(k), where k is the number of even elements in the input list.



Last Updated : 15 Mar, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads