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
test_list = [ 3 , 1 , 2 , 5 , 4 , 10 , 6 , 9 ]
print ( "The original list is : " + str (test_list))
res = []
for idx, ele in enumerate (test_list):
if idx = = ele:
res.append(ele)
print ( "Filtered elements : " + str (res))
|
Output
The 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
test_list = [ 3 , 1 , 2 , 5 , 4 , 10 , 6 , 9 ]
print ( "The original list is : " + str (test_list))
res = [ele for idx, ele in enumerate (test_list) if idx = = ele]
print ( "Filtered elements : " + str (res))
|
Output
The 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
test_list = [ 3 , 1 , 2 , 5 , 4 , 10 , 6 , 9 ]
print ( "The original list is : " + str (test_list))
res = []
for i in range ( 0 , len (test_list)):
if (i = = test_list[i]):
res.append(test_list[i])
print ( "Filtered elements : " + str (res))
|
Output
The 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
test_list = [ 3 , 1 , 2 , 5 , 4 , 10 , 6 , 9 ]
print ( "The original list is : " + str (test_list))
res = np.where(np.array(test_list) = = np.arange( len (test_list)))[ 0 ]
print ( "Filtered elements : " + str ( list (res)))
|
Output
The 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
test_list = [ 3 , 1 , 2 , 5 , 4 , 10 , 6 , 9 ]
print ( "The original list is : " + str (test_list))
res = list ( filter ( lambda x: x[ 0 ] = = x[ 1 ], enumerate (test_list)))
res = [ele for idx, ele in res]
print ( "Filtered elements : " + str (res))
|
Output
The 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 | 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 - Records with Value at K index
Sometimes, while working with records, we might have a problem in which we need to find all the tuples of elements for a particular value at a particular Kth position of tuple. This seems to be a peculiar problem but while working with many keys in records, we encounter this problem. Letâs discuss c
8 min read
Python - Append Multiple elements in set
In Python, sets are an unordered and mutable collection of data type what does not contains any duplicate elements. In this article, we will learn how to append multiple elements in the set at once. Example: Input: test_set = {6, 4, 2, 7, 9}, up_ele = [1, 5, 10]Output: {1, 2, 4, 5, 6, 7, 9, 10}Expla
4 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
Replace index elements with elements in Other List-Python
The task of replacing index elements with elements from another list involves mapping the indices from one list to the corresponding elements in a second list. For each index in the first list, the element at that index is retrieved from the second list and stored in a new result list. For example,
4 min read
Python - Index Directory of Elements
Given a list of elements, the task is to write a python program to compute all the indices of all the elements. Examples: Input: test_list = [7, 6, 3, 7, 8, 3, 6, 7, 8] Output: {8: [4, 8], 3: [2, 5], 6: [1, 6], 7: [0, 3, 7]} Explanation: 8 occurs at 4th and 8th index, 3 occurs at 2nd and 5th index a
3 min read
Python - Dictionary with Index as Value
We are having a list we need to find index of each element and store it in form of dictionary. For example, a = ['a', 'b', 'c', 'd'] we need to find index of each elements in list so that output should be {'a': 0, 'b': 1, 'c': 2, 'd': 3}. Using Dictionary ComprehensionWe can use dictionary comprehen
2 min read