5 Best Ways to Find Indices of List Elements in Another List in Python

πŸ’‘ Problem Formulation: Python developers are often required to determine the positions of elements from one list in another list. For instance, given the list ['a', 'b', 'c'] and another list ['b', 'a', 'd', 'c', 'e'], the goal is to create a program that returns the indices of the first list’s elements in the second list, producing [1, 0, 3] as the output.

Method 1: Using a For-Loop and index() Function

This method involves iterating over the elements of the first list and using the index() function to find their positions in the second list. It is straightforward and suitable for beginners to understand and implement.

Here’s an example:

list1 = ['a', 'b', 'c']
list2 = ['b', 'a', 'd', 'c', 'e']
indices = [list2.index(x) for x in list1 if x in list2]

print(indices)

Output:

[1, 0, 3]

This code snippet generates a new list indices through a list comprehension, which finds the index of each element x of list1 in list2, provided the element exists in list2.

Method 2: Using the enumerate() Function and a Dictionary

By utilizing the enumerate() function, you can create a dictionary that maps each element of the second list to its index, which can then be used to look up the index of each element in the first list more efficiently, especially for large lists.

Here’s an example:

list1 = ['a', 'b', 'c']
list2 = ['b', 'a', 'd', 'c', 'e']
index_map = {value: index for index, value in enumerate(list2)}
indices = [index_map.get(x) for x in list1 if x in index_map]

print(indices)

Output:

[1, 0, 3]

The code creates a dictionary index_map that holds elements from list2 as keys and their indices as values. Then, it compiles a list of indices for elements in list1 by mapping them through this dictionary.

Method 3: Using List Comprehension and the index() Function with a Try-Except Block

To avoid errors when an element from the first list is not present in the second list, a try-except block can be used within the list comprehension. This approach combines the simplicity of the index lookup with error handling.

Here’s an example:

list1 = ['a', 'b', 'c']
list2 = ['b', 'a', 'd', 'e']
indices = []

for x in list1:
    try:
        index = list2.index(x)
        indices.append(index)
    except ValueError:
        continue
    
print(indices)

Output:

[1, 0]

This code attempts to find the index of each element from list1 within list2. If the element is not found, Python raises a ValueError, which is caught by the except block, allowing the loop to continue without breaking.

Method 4: Using List Comprehension with a Conditional Test

Instead of handling exceptions, you can first test if the element exists in the second list by using a conditional within the list comprehension. This method is cleaner than using try-except when expecting missing elements.

Here’s an example:

list1 = ['a', 'b', 'c']
list2 = ['b', 'a', 'd', 'c', 'e']
indices = [list2.index(x) for x in list1 if x in list2]

print(indices)

Output:

[1, 0, 3]

This list comprehension checks if x is in list2 before using list2.index(x), preventing a ValueError from being raised, as we only attempt to get the index of x if it exists in list2.

Bonus One-Liner Method 5: Using the filter() Function with a Lambda Expression

A one-liner solution can be written using the filter() function along with a lambda expression. This method is concise and functional but might not be as readable for beginners.

Here’s an example:

list1 = ['a', 'b', 'c']
list2 = ['b', 'a', 'd', 'c', 'e']
indices = list(filter(lambda x: x in list2, [list2.index(x) for x in list1]))

print(indices)

Output:

[1, 0, 3]

The lambda function filters out all the elements of list1 which are not present in list2 before passing them to the list comprehension for index retrieval.

Summary/Discussion

  • Method 1: Using a For-Loop and index() Function. Strengths: Simple and easy to understand. Weaknesses: Not very efficient with large lists, as index() is called for every element.
  • Method 2: Using the enumerate() Function and a Dictionary. Strengths: More efficient for large lists; lookups are constant time operations. Weaknesses: Requires additional space for the dictionary.
  • Method 3: Using List Comprehension with Try-Except Block. Strengths: Contains error handling. Weaknesses: Exception handling can be costly.
  • Method 4: Using List Comprehension with a Conditional Test. Strengths: Cleaner and safer for lists with expected missing elements. Weaknesses: Might be less efficient than method 2 if there are many duplicates in list2, as in is checked for each element.
  • Method 5: Bonus One-Liner using filter() Function with a Lambda Expression. Strengths: Concise one-liner. Weaknesses: Less readable for some, and can be slower due to lambda overhead.