Open In App

Python | Extract similar index elements

Last Updated : 27 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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 loop + zip() The combination of above functions can be used to solve this problem. In this, we extract combine the index elements using zip and then extract and check for similarity using conditional statement in loop. 

Python3




# Python3 code to demonstrate working of
# Extracting similar index elements
# using loop + zip()
 
# initialize lists
test_list1 = ["a", "b", "c", "d"]
test_list2 = ["g", "b", "s", "d"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# Extracting similar index elements
# using loop + zip()
res = []
for i, j in zip(test_list1, test_list2):
    if i == j:
        res.append(i)
 
# printing result
print("Similar index elements in lists : " + str(res))


Output : 

The original list 1 : ['a', 'b', 'c', 'd']
The original list 2 : ['g', 'b', 's', 'd']
Similar index elements in lists : ['b', 'd']

Time Complexity: O(n*n), where n is the length of the input list. This is because we’re using loop + zip() which has a time complexity of O(n*n) in the worst case.
Auxiliary Space: O(n), as we’re using additional space res other than the input list itself with the same size of input list.

Method #2 : Using zip() + list comprehension Combination of these functionalities can also be used to solve this problem. In this, we use similar method as above, just a shorthand logic compressed using list comprehension. 

Python3




# Python3 code to demonstrate working of
# Extracting similar index elements
# using list comprehension + zip()
 
# initialize lists
test_list1 = ["a", "b", "c", "d"]
test_list2 = ["g", "b", "s", "d"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# Extracting similar index elements
# using list comprehension + zip()
res = [i for i, j in zip(test_list1, test_list2) if i == j]
 
# printing result
print("Similar index elements in lists : " + str(res))


Output : 

The original list 1 : ['a', 'b', 'c', 'd']
The original list 2 : ['g', 'b', 's', 'd']
Similar index elements in lists : ['b', 'd']

Method #3: Using numpy.intersect1d()

Note: install numpy module using command “pip install numpy”

This method makes use of the numpy library. The intersect1d function returns the sorted, unique values that are in both of the input arrays.

Python3




# Python3 code to demonstrate working of
# Extracting similar index elements
# using numpy.intersect1d()
 
import numpy as np
 
# initialize lists
test_list1 = ["a", "b", "c", "d"]
test_list2 = ["g", "b", "s", "d"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : " + str(test_list2))
 
# Extracting similar index elements
# using numpy.intersect1d()
res = np.intersect1d(test_list1, test_list2)
 
# printing result
print("Similar index elements in lists : " + str(res))
 
#this code is contributed by edula vinay kumar reddy


Output :

The original list 1 : ['a', 'b', 'c', 'd']
The original list 2 : ['g', 'b', 's', 'd']
Similar index elements in lists : ['b' 'd']

Method #4:  Using map() + lambda and filter()

Step-by-step approach:

  1. Initialize two lists test_list1 and test_list2.
  2. Create a lambda function that takes two arguments and checks whether they are equal or not. If they are equal, return the first argument, otherwise return None.
  3. Use the map() function to apply the lambda function to each pair of elements in test_list1 and test_list2.
  4. Convert the resulting map object into a list using the list() function.
  5. Use the filter() function to remove any None values from the list.
  6. Convert the resulting filter object into a list using the list() function.
  7. Print the resulting list using the print() function.

Python3




# Python3 code to demonstrate working of
# Extracting similar index elements
 
# initialize lists
test_list1 = ["a", "b", "c", "d"]
test_list2 = ["g", "b", "s", "d"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : "+ str(test_list2))
 
# Extracting similar index elements
res = list(filter(lambda x: x != None, list(map(lambda x, y: x if x == y else None, test_list1, test_list2))))
 
 
# printing result
print("Similar index elements in lists : " + str(res))


Output

The original list 1 : ['a', 'b', 'c', 'd']
The original list 2 : ['g', 'b', 's', 'd']
Similar index elements in lists : ['b', 'd']

Time complexity: O(n) where n is the length of the input lists. 
Auxiliary Space: O(n) where n is the length of the input lists.   

Method #5:  Using reduce():

Step-by-step approach:

  • Initialize two lists.
  • Using zip, combine the corresponding elements of the two lists into a list of pairs.
  • Use reduce to iterate over the pairs and accumulate the result in a list.
  • For each pair, if the elements are equal, add the first element to the accumulator list. If not, skip the pair and
  • return the accumulator list.
  • Print the result.

Python3




from functools import reduce
 
# initialize lists
test_list1 = ["a", "b", "c", "d"]
test_list2 = ["g", "b", "s", "d"]
 
# printing original lists
print("The original list 1 : " + str(test_list1))
print("The original list 2 : "+ str(test_list2))
 
# Extracting similar index elements
res = reduce(lambda acc, pair: acc + [pair[0]] if pair[0] == pair[1] else acc, zip(test_list1, test_list2), [])
 
# printing result
print("Similar index elements in lists : " + str(res))
#This code is contributed by Pushpa.


Output

The original list 1 : ['a', 'b', 'c', 'd']
The original list 2 : ['g', 'b', 's', 'd']
Similar index elements in lists : ['b', 'd']

Time complexity: O(n), where n is the length of the input lists. This is because reduce and zip both iterate over the lists once.
Auxiliary Space: O(n), where n is the length of the input lists. This is because the zip function creates a list of pairs with length n, and the reduce function creates an accumulator list with length at most n.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads