Saturday, November 16, 2024
Google search engine
HomeLanguagesPython – Elements with same index

Python – Elements with same index

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))


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




# 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))


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




# 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))


Output

The original list is : [3, 1, 2, 5, 4, 10, 6, 9]
Filtered elements : [1, 2, 4, 6]

Method #4: Using numpy library:

  1. Create a numpy array from the given list using np.array() function.
  2. Create another numpy array using np.arange(len(test_list)), which creates an array with values from 0 to len(test_list)-1.
  3. 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.
  4. Use np.where() function to get the indices of True values in the boolean array.
  5. Convert the resulting numpy array of indices to a Python list using list() function.
  6. 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


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




# 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))


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.

RELATED ARTICLES

Most Popular

Recent Comments