# Python – Retain K match index values from other list

Sometimes, while working with Python lists, we can have a problem in which we need to retain only the strings with match a particular value from the corresponding list at same index. This can have application in many domains. Lets discuss certain ways in which this task can be performed.

Method #1 : Using list comprehension + zip() The combination of above functionalities can be used to perform this task. In this, we extract the list after selective zipping of both the list matching K.

## Python3

 `# Python3 code to demonstrate ``# Retain K match index values from other list``# using zip() + list comprehension` `# Initializing lists``test_list1 ``=` `[``'Gfg'``, ``'is'``, ``'best'``, ``'for'``, ``'Geeks'``, ``'and'``, ``'CS'``]``test_list2 ``=` `[``4``, ``1``, ``4``, ``3``, ``4``, ``2``, ``4``]` `# printing original lists``print``("The original ``list` `1` `is` `: " ``+` `str``(test_list1))``print``("The original ``list` `2` `is` `: " ``+` `str``(test_list2))` `# Initializing K ``K ``=` `4` `# Group elements from Dual List Matrix``# using zip() + list comprehension``res ``=` `[x ``for` `x, y ``in` `zip``(test_list1, test_list2) ``if` `y ``=``=` `K]``            ` `# printing result ``print` `("The filtered ``list` `: " ``+` `str``(res))`

Output :

The original list 1 is : [‘Gfg’, ‘is’, ‘best’, ‘for’, ‘Geeks’, ‘and’, ‘CS’] The original list 2 is : [4, 1, 4, 3, 4, 2, 4] The filtered list : [‘Gfg’, ‘best’, ‘Geeks’, ‘CS’]

Time Complexity: O(n)
Auxiliary Space: O(1)

Method #2 : Using compress() + list comprehension This is yet another way in which this task can be performed. In this, we use compress() instead of zip() to solve the problem.

## Python3

 `# Python3 code to demonstrate ``# Retain K match index values from other list``# using compress + list comprehension``from` `itertools ``import` `compress` `# Initializing lists``test_list1 ``=` `[``'Gfg'``, ``'is'``, ``'best'``, ``'for'``, ``'Geeks'``, ``'and'``, ``'CS'``]``test_list2 ``=` `[``4``, ``1``, ``4``, ``3``, ``4``, ``2``, ``4``]` `# printing original lists``print``("The original ``list` `1` `is` `: " ``+` `str``(test_list1))``print``("The original ``list` `2` `is` `: " ``+` `str``(test_list2))` `# Initializing K ``K ``=` `4` `# Group elements from Dual List Matrix``# using compress + list comprehension``res ``=` `list``(compress(test_list1, ``map``(``lambda` `ele: ele ``=``=` `K, test_list2)))``            ` `# printing result ``print` `("The filtered ``list` `: " ``+` `str``(res))`

Output :

The original list 1 is : [‘Gfg’, ‘is’, ‘best’, ‘for’, ‘Geeks’, ‘and’, ‘CS’] The original list 2 is : [4, 1, 4, 3, 4, 2, 4] The filtered list : [‘Gfg’, ‘best’, ‘Geeks’, ‘CS’]

Time Complexity: O(n)
Auxiliary Space: O(k)

Method #3 : using filter + lambda

This is yet another way in which this task can be performed. In this, we use filter() and lambda to solve the problem.

## Python3

 `# Python3 code to demonstrate ``# Retain K match index values from other list``# using filter + lambda``  ` `# Initializing lists``test_list1 ``=` `[``'Gfg'``, ``'is'``, ``'best'``, ``'for'``, ``'Geeks'``, ``'and'``, ``'CS'``]``test_list2 ``=` `[``4``, ``1``, ``4``, ``3``, ``4``, ``2``, ``4``]``  ` `# printing original lists``print``(``"The original list 1 is : "` `+` `str``(test_list1))``print``(``"The original list 2 is : "` `+` `str``(test_list2))``  ` `# Initializing K ``K ``=` `4``  ` `# Group elements from Dual List Matrix``# using filter + lambda``res ``=` `[i[``0``] ``for` `i ``in` `list``(``filter``(``lambda` `x : x[``1``] ``=``=` `K, ``zip``(test_list1, test_list2)))]``              ` `# printing result ``print` `(``"The filtered list : "` `+` `str``(res))`

Output
```The original list 1 is : ['Gfg', 'is', 'best', 'for', 'Geeks', 'and', 'CS']
The original list 2 is : [4, 1, 4, 3, 4, 2, 4]
The filtered list : ['Gfg', 'best', 'Geeks', 'CS']```

Time complexity: O(n)
Auxiliary Space: O(n)

Method#4: Using Recursive method.

The function works recursively in the following way:

1. If either lst1 or lst2 is empty, return an empty list.
2. If the first element of lst2 matches the value of k, append the first element of lst1 to the result, and call the function again with the remaining elements of lst1 and lst2.
3. If the first element of lst2 does not match the value of k, call the function again with the remaining elements of lst1 and lst2.
4. Finally, the function returns the result as a list.

## Python3

 `def` `retain_k_index_values_recursive(lst1, lst2, k):``    ``if` `not` `lst1 ``or` `not` `lst2:``        ``return` `[]``    ``elif` `lst2[``0``] ``=``=` `k:``        ``return` `[lst1[``0``]] ``+` `retain_k_index_values_recursive(lst1[``1``:], lst2[``1``:], k)``    ``else``:``        ``return` `retain_k_index_values_recursive(lst1[``1``:], lst2[``1``:], k)``# Initializing lists``test_list1 ``=` `[``'Gfg'``, ``'is'``, ``'best'``, ``'for'``, ``'Geeks'``, ``'and'``, ``'CS'``]``test_list2 ``=` `[``4``, ``1``, ``4``, ``3``, ``4``, ``2``, ``4``]`` ` `# printing original lists``print``(``"The original list 1 is : "` `+` `str``(test_list1))``print``(``"The original list 2 is : "` `+` `str``(test_list2))`` ` `# Initializing K``K ``=` `4``res ``=` `retain_k_index_values_recursive(test_list1,test_list2,K)``# printing result``print``(``"The filtered list : "` `+` `str``(res))``#this code contributed by tvsk`

Output
```The original list 1 is : ['Gfg', 'is', 'best', 'for', 'Geeks', 'and', 'CS']
The original list 2 is : [4, 1, 4, 3, 4, 2, 4]
The filtered list : ['Gfg', 'best', 'Geeks', 'CS']```

The time complexity of the function is O(n), where n is the length of the input lists.

The auxiliary space is also O(n), because the function uses a recursive call stack to store intermediate results.

Method#5: Using for loop

Here’s the step by step algorithm for the for loop method:

1. Initialize two lists, test_list1 and test_list2, and the integer value K.
2. Initialize an empty list res to store the filtered values.
3. Traverse through the test_list2 using a for loop.
4. For each element x in test_list2, compare it with K.
5. If x is equal to K, append the corresponding element from test_list1 to res.
6. Once the loop is completed, the res list will contain all the elements from test_list1 that have a matching index value in test_list2 equal to K.
7. Print the res list.

## Python3

 `# Initializing lists``test_list1 ``=` `[``'Gfg'``, ``'is'``, ``'best'``, ``'for'``, ``'Geeks'``, ``'and'``, ``'CS'``]``test_list2 ``=` `[``4``, ``1``, ``4``, ``3``, ``4``, ``2``, ``4``]` `# Initializing K``K ``=` `4` `# Initialize an empty list``res ``=` `[]` `# Traverse through the lists and compare elements``for` `i ``in` `range``(``len``(test_list2)):``    ``if` `test_list2[i] ``=``=` `K:``        ``res.append(test_list1[i])` `# Printing the filtered list``print``(``"The filtered list : "``, res)``#This code is contributed by Vinay Pinjala.`

Output
`The filtered list :  ['Gfg', 'best', 'Geeks', 'CS']`

Time Complexity: O(n), where n is the length of the test_list2 list. This is because the for loop iterates through each element in the list once, and the time it takes to perform the comparison and append operation is constant.

Auxiliary Space: O(k), where k is the number of elements in test_list1 that have a matching index value in test_list2 equal to K. This is because we are only storing the matching elements in the res list, and the size of this list is directly proportional to the number of matching elements.

Method 6: uses the enumerate() function

Use the enumerate() function to iterate through test_list2 while keeping track of the index of each element. Then, it uses a loop to check if the current element in test_list2 is equal to K, and if it is, it appends the corresponding element from test_list1 to the res list.

## Python3

 `# Python3 code to demonstrate ``# Retain K match index values from other list``# using enumerate() and a loop` `# Initializing lists``test_list1 ``=` `[``'Gfg'``, ``'is'``, ``'best'``, ``'for'``, ``'Geeks'``, ``'and'``, ``'CS'``]``test_list2 ``=` `[``4``, ``1``, ``4``, ``3``, ``4``, ``2``, ``4``]` `# printing original lists``print``(``"The original list 1 is : "` `+` `str``(test_list1))``print``(``"The original list 2 is : "` `+` `str``(test_list2))` `# Initializing K ``K ``=` `4` `# Using enumerate() and a loop to filter elements``res ``=` `[]``for` `i, val ``in` `enumerate``(test_list2):``    ``if` `val ``=``=` `K:``        ``res.append(test_list1[i])` `# printing result ``print``(``"The filtered list : "` `+` `str``(res))`

Output
```The original list 1 is : ['Gfg', 'is', 'best', 'for', 'Geeks', 'and', 'CS']
The original list 2 is : [4, 1, 4, 3, 4, 2, 4]
The filtered list : ['Gfg', 'best', 'Geeks', 'CS']```

Time complexity: O(n), where n is the length of test_list2.
Auxiliary space: O(m), where m is the number of elements in test_list2 that are equal to K.

Method #7: Using a generator function

Using a generator function. A generator function is a special type of function that can be used to create an iterator. It allows us to generate a sequence of values on the fly, rather than creating a list of all the values at once.

• Start by initializing two lists test_list1 and test_list2 with some values.
• Print the original lists to verify the input.
• Initialize a variable K with a value (in this case, 4).
• Use zip() function to group the elements of test_list1 and test_list2 together as pairs.
• Use a list comprehension to iterate over the pairs and filter out only those pairs where the second element (y) is equal to K.
• Extract the first element (x) from the filtered pairs and append it to a list res.
• Print the final filtered list res to verify the output.

## Python3

 `def` `filter_by_index(lst1, lst2, k):``    ``for` `x, y ``in` `zip``(lst1, lst2):``        ``if` `y ``=``=` `k:``            ``yield` `x` `# Initializing lists``test_list1 ``=` `[``'Gfg'``, ``'is'``, ``'best'``, ``'for'``, ``'Geeks'``, ``'and'``, ``'CS'``]``test_list2 ``=` `[``4``, ``1``, ``4``, ``3``, ``4``, ``2``, ``4``]` `# printing original lists``print``(``"The original list 1 is : "` `+` `str``(test_list1))``print``(``"The original list 2 is : "` `+` `str``(test_list2))` `# Initializing K ``K ``=` `4` `# using generator function``res ``=` `list``(filter_by_index(test_list1, test_list2, K))` `# printing result ``print` `(``"The filtered list : "` `+` `str``(res))`

Output
```The original list 1 is : ['Gfg', 'is', 'best', 'for', 'Geeks', 'and', 'CS']
The original list 2 is : [4, 1, 4, 3, 4, 2, 4]
The filtered list : ['Gfg', 'best', 'Geeks', 'CS']```

Time complexity: O(n) where n is the length of the input list
Auxiliary space: O(1) (since we are using a generator function)

Don't miss your chance to ride the wave of the data revolution! Every industry is scaling new heights by tapping into the power of data. Sharpen your skills and become a part of the hottest trend in the 21st century.

Dive into the future of technology - explore the Complete Machine Learning and Data Science Program by GeeksforGeeks and stay ahead of the curve.

Previous
Next