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 - 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 | 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
Python - Test Common Elements Order Sometimes, while working with lists, we can have a problem in which we need to test if list contains common elements. This type of problem has been dealt many times and has lot of solutions. But sometimes, we might have a problem in which we need to check that those common elements appear in same or
4 min read