Python - Elements with same index
Last Updated :
28 Apr, 2023
Given a List, get all elements that are at their index value.
Input : test_list = [3, 1, 8, 5, 4, 10, 6, 9]
Output : [1, 4, 6]
Explanation : These elements are at same position as its number.
Input : test_list = [3, 10, 8, 5, 14, 10, 16, 9]
Output : []
Explanation : No number at its index.
Method #1: Using loop
In this, we check for each element, if it equates to its index, it's added to the result list.
Python3
# Python3 code to demonstrate working of
# Elements with same index
# Using loop
# Initializing list
test_list = [3, 1, 2, 5, 4, 10, 6, 9]
# Printing original list
print("The original list is : " + str(test_list))
# Enumerating to get index and element
res = []
for idx, ele in enumerate(test_list):
if idx == ele:
res.append(ele)
# Printing result
print("Filtered elements : " + str(res))
OutputThe original list is : [3, 1, 2, 5, 4, 10, 6, 9]
Filtered elements : [1, 2, 4, 6]
Time Complexity: O(n)
Auxiliary Space: O(n)
Method #2 : Using list comprehension + enumerate()
In this, we perform a similar function as the above method, the change being we use list comprehension to make the solution compact.
Python3
# Python3 code to demonstrate working of
# Elements with same index
# Using list comprehension + enumerate()
# Initializing list
test_list = [3, 1, 2, 5, 4, 10, 6, 9]
# Printing original list
print("The original list is : " + str(test_list))
# Enumerating to get index and element
res = [ele for idx, ele in enumerate(test_list) if idx == ele]
# Printing result
print("Filtered elements : " + str(res))
OutputThe original list is : [3, 1, 2, 5, 4, 10, 6, 9]
Filtered elements : [1, 2, 4, 6]
Time Complexity: O(n) where n is the number of elements in the list “test_list”. This is because we’re using the list comprehension + enumerate() function which all has a time complexity of O(n) in the worst case.
Auxiliary Space: O(1), no extra space is required.
Method #3: Using for loop
Python3
# Python3 code to demonstrate working of
# Elements with same index
# Using loop
# initializing list
test_list = [3, 1, 2, 5, 4, 10, 6, 9]
# printing original list
print("The original list is : " + str(test_list))
# enumerate to get index and element
res = []
for i in range(0,len(test_list)):
if(i==test_list[i]):
res.append(test_list[i])
# printing result
print("Filtered elements : " + str(res))
OutputThe original list is : [3, 1, 2, 5, 4, 10, 6, 9]
Filtered elements : [1, 2, 4, 6]
Method #4: Using numpy library:
- Create a numpy array from the given list using np.array() function.
- Create another numpy array using np.arange(len(test_list)), which creates an array with values from 0 to len(test_list)-1.
- Compare the two numpy arrays element-wise using the equality operator (==). This returns a boolean array with True at positions where the corresponding elements are equal, and False otherwise.
- Use np.where() function to get the indices of True values in the boolean array.
- Convert the resulting numpy array of indices to a Python list using list() function.
- Print the filtered elements using the list of indices.
Python3
import numpy as np
# Initialize list of numbers
test_list = [3, 1, 2, 5, 4, 10, 6, 9]
# Printing original list
print("The original list is : " + str(test_list))
# Converting list to numpy array and compare with the range
# of the length of the array
# np.arange(len(test_list)) returns an array of the same length
# as test_list with elements ranging from 0 to len(test_list)-1
# np.where() returns the indices where the two arrays are equal
res = np.where(np.array(test_list) == np.arange(len(test_list)))[0]
# convert resulting numpy array to a list and print
print("Filtered elements : " + str(list(res)))
# This code is contributed by Jyothi pinjala
OutputThe original list is : [3, 1, 2, 5, 4, 10, 6, 9]
Filtered elements : [1, 2, 4, 6]
Time complexity: O(n), where n is the length of the input list. This is because creating numpy arrays from a list, comparing them element-wise, and finding indices of True values in the boolean array all take O(n) time.
Auxiliary Space: O(n), where n is the length of the input list. This is because two numpy arrays of size n are created, and a list of filtered indices is created which can have at most n elements.
Method #5 using the filter() function:
Python3
# Python3 code to demonstrate working of
# Elements with same index
# Using filter() function
# Initializing list
test_list = [3, 1, 2, 5, 4, 10, 6, 9]
# Printing original list
print("The original list is : " + str(test_list))
# using filter() and lambda function to get elements with same index
res = list(filter(lambda x: x[0] == x[1], enumerate(test_list)))
# extracting the elements from the result
res = [ele for idx, ele in res]
# printing result
print("Filtered elements : " + str(res))
OutputThe original list is : [3, 1, 2, 5, 4, 10, 6, 9]
Filtered elements : [1, 2, 4, 6]
Time complexity: O(n), where n is the length of the input list.
Auxiliary space: O(m), where m is the number of elements in the input list that have the same index and value.
Similar Reads
Python - Filter tuple with all same elements
Given List of tuples, filter tuples that have same values. Input : test_list = [(5, 6, 5, 5), (6, 6, 6), (9, 10)] Output : [(6, 6, 6)] Explanation : 1 tuple with same elements. Input : test_list = [(5, 6, 5, 5), (6, 5, 6), (9, 10)] Output : [] Explanation : No tuple with same elements. Method #1 : U
4 min read
Python - Elements with K lists similar index value
Sometimes, while working with data, we can have a problem in which we need to get elements which are similar in K lists in particular index. This can have application in many domains such as day-day and other domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using z
5 min read
Python - Index Ranks of Elements
Given a list of elements, our task is to get the index ranks of each element. Index Rank of Number = (Sum of occurrence indices of number) / number Input : test_list = [3, 4, 6, 5, 3, 4, 9, 1, 2, 1, 8, 3, 2, 3, 9] Output : [(1, 16.0), (2, 10.0), (3, 9.333333333333334), (4, 1.5), (5, 0.6), (6, 0.3333
3 min read
Python - Element Index in Range Tuples
Sometimes, while working with Python data, we can have a problem in which we need to find the element position in continuous equi ranged tuples in list. This problem has applications in many domains including day-day programming and competitive programming. Let's discuss certain ways in which this t
7 min read
Python | Extract similar index elements
Sometimes, while working with Python data, we can have a problem in which we require to extract the values across multiple lists which are having similar index values. This kind of problem can come in many domains. Let's discuss certain ways in which this problem can be solved. Method #1 : Using loo
6 min read
Python - Similar index elements frequency
Sometimes, while working with Python list, we can have a problem in which we need to check if one element has similar index occurrence in other list. This can have possible application in many domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using sum() + zip() The
7 min read
Search Elements in a Matrix - Python
The task of searching for elements in a matrix in Python involves checking if a specific value exists within a 2D list or array. The goal is to efficiently determine whether the desired element is present in any row or column of the matrix. For example, given a matrix a = [[4, 5, 6], [10, 2, 13], [1
3 min read
Python - Similar other index element of K
Given List of elements, other list and K, extract all the similar other list index elements if element is K in List. Input : test_list = [6, 4, 6, 3, 6], arg_list = [7, 5, 4, 6, 3], K = 6 Output : [7, 4, 3] Explanation : 7, 4 and 3 correspond to occurrences of 6 in first list.Input : test_list = [2,
7 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
Python - Remove similar index elements in Strings
Given two strings, removed all elements from both, which are the same at similar index. Input : test_str1 = 'geels', test_str2 = 'beaks' Output : gel, bak Explanation : e and s are removed as occur in same indices. Input : test_str1 = 'geeks', test_str2 = 'geeks' Output : '', '' Explanation : Same s
6 min read