Python - Get Indices of Even Elements from list
Last Updated :
15 Mar, 2023
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))
OutputThe 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))
OutputThe 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)
OutputThe 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.
OutputThe 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.
OutputThe 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.
OutputThe 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:
- Convert the input list to a pandas Series.
- Filter the series to select the elements that are even using a boolean mask created using the modulo operator.
- Extract the index of the selected elements using the index attribute of the series.
- Convert the resulting pandas Index object to a list using the tolist() method.
- 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.
Similar Reads
Python - Indices of atmost K elements in list
Many times we might have problem in which we need to find indices rather than the actual numbers and more often, the result is conditioned. First approach coming to mind can be a simple index function and get indices less than or equal than particular number, but this approach fails in case of dupli
7 min read
Get first and last elements of a list in Python
The task of getting the first and last elements of a list in Python involves retrieving the initial and final values from a given list. For example, given a list [1, 5, 6, 7, 4], the first element is 1 and the last element is 4, resulting in [1, 4]. Using indexingThis is the most straightforward way
3 min read
Get the Last Element of List in Python
In this article, we will learn about different ways of getting the last element of a list in Python. For example, consider a list:Input: list = [1, 3, 34, 12, 6]Output: 6Explanation: Last element of the list l in the above example is 6.Let's explore various methods of doing it in Python:1. Using Neg
2 min read
Python - Find Kth Even Element
Given a List, extract Kth occurrence of Even Element. Input : test_list = [4, 6, 2, 3, 8, 9, 10, 11], K = 3 Output : 8 Explanation : K = 3, i.e 0 based index, 4, 6, 2 and 4th is 8. Input : test_list = [4, 6, 2, 3, 8, 9, 10, 11], K = 2 Output : 2 Explanation : K = 2, i.e 0 based index, 4, 6, and 3rd
5 min read
Python - Remove elements at Indices in List
Given List, remove all the elements present in the indices list in Python. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2, 4, 5]Â Output : [5, 6, 7, 2, 10]Â Explanation : 3, 6, and 1 has been removed. Input : test_list = [5, 6, 3, 7, 8, 1, 2, 10], idx_list = [2]Â Output : [5, 6, 7, 8,
7 min read
Get first element from a List of tuples - Python
The goal here is to extract the first element from each tuple in a list of tuples. For example, given a list [(1, 'sravan'), (2, 'ojaswi'), (3, 'bobby')], we want to retrieve [1, 2, 3], which represents the first element of each tuple. There are several ways to achieve this, each varying in terms of
2 min read
Python - Odd elements indices
Sometimes, while working with Python lists, we can have a problem in which we wish to find Odd 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âs discuss certain way to find indic
7 min read
How to get specific elements from list in python
In this article, we will learn how to get specific item(s) from given list. There are multiple methods to achieve this. Most simple method is accessing list item by Index. Pythona = [1, 'geeks', 3, 'for', 5] # accessing specific list item with their indices item1 = a[1] item3 = a[2] item5 = a[4] # n
3 min read
Extract Elements from a Python List
When working with lists in Python, we often need to extract specific elements. The easiest way to extract an element from a list is by using its index. Python uses zero-based indexing, meaning the first element is at index 0. Pythonx = [10, 20, 30, 40, 50] # Extracts the last element a = x[0] print(
2 min read
Python - Negative index of Element in List
We are given a list we need to find the negative index of that element. For example, we are having a list li = [10, 20, 30, 40, 50] and the given element is 30 we need to fin the negative index of it so that given output should be -3.Using index()index() method in Python searches for the first occur
3 min read