Python | Extract similar index elements
Last Updated :
27 Apr, 2023
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:
- Initialize two lists test_list1 and test_list2.
- 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.
- Use the map() function to apply the lambda function to each pair of elements in test_list1 and test_list2.
- Convert the resulting map object into a list using the list() function.
- Use the filter() function to remove any None values from the list.
- Convert the resulting filter object into a list using the list() function.
- 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))
OutputThe 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.
OutputThe 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.
Similar Reads
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 - Similar index elements Matrix
Sometimes, while working with data, we can have a problem in which we need to perform the construction of matrix from lists element vertically than horizontally. This kind of application can come in Data Science domains in which we need to construct Matrix from several lists. Lets discuss certain wa
7 min read
Python - Group Records on Similar index elements
Sometimes, while working with Python records, we can have a problem in which we need to perform grouping of particular index of tuple, on basis of similarity of rest of indices. This type of problems can have possible applications in Web development domain. Let's discuss certain ways in which this t
6 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 - 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
5 min read
Python - Extract Monodigit elements
Given List of numbers, extract all numbers with only similar digit. Input : test_list = [463, 888, 123, 'aaa', 112, 111, 'gfg', 939, 4, 'ccc'] Output : [888, 'aaa', 111, 4, 'ccc'] Explanation : All elements having single unique digit or character. Input : test_list = [463, "GFG", 8838, 43, 991] Outp
6 min read
Python - Group similar elements into Matrix
Sometimes, while working with Python Matrix, we can have a problem in which we need to perform grouping of all the elements with are the same. This kind of problem can have applications in data domains. Let's discuss certain ways in which this task can be performed. Input : test_list = [1, 3, 4, 4,
8 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
Python - Filter index similar values
Sometimes, while working with Python dictionaries, we can have a problem in which we need to extract all the values in values lists that match the filtered indices from matching values from list with some key in dictionary. This kind of application can occur in web development. Input : test_dict = {
4 min read
Python | Equate two list index elements
Sometimes we need to link two list from the point of view of their index elements and this kind of problem comes mostly in places where we need to display in formatted form the linkage of two lists with one another. This a very specific problem, but can be useful whenever we need a possible solution
8 min read