How to find the intersection of two lists (values that exist in both lists) in Python

1 Answer

0 votes
from typing import List, TypeVar

T = TypeVar("T")


def find_list_intersection(list1: List[T], list2: List[T]) -> List[T]:
    """Finds the unique intersection of two lists (values that exist in both).

    Maintains order based on the first occurrence in the first list.

    Time Complexity:  O(N + M) where N and M are the lengths of the lists.
    Space Complexity: O(min(N, M)) auxiliary space for the set lookups.

    Args:
        list1: The first list sequence.
        list2: The second list sequence.

    Returns:
        A list of unique elements present in both input lists.
    """
    # Convert the second list to a set for O(1) average lookup time
    lookup_set = set(list2)

    # Use a set to track already matched items to guarantee uniqueness
    seen = set()
    result = []

    # Iterate through list1 to preserve initial ordering of matches
    for item in list1:
        if item in lookup_set and item not in seen:
            result.append(item)
            seen.add(item)

    return result


# --- Usage Example ---
if __name__ == "__main__":
    lst1 = [5, 7, 1, 1, 3, 0, 6, 2]
    lst2 = [2, 8, 8, 6, 9, 3, 3, 4, 4]

    intersection = find_list_intersection(lst1, lst2)

    print(f"List 1:       {lst1}")
    print(f"List 2:       {lst2}")
    print(f"Intersection: {intersection}")



'''
run:

List 1:       [5, 7, 1, 1, 3, 0, 6, 2]
List 2:       [2, 8, 8, 6, 9, 3, 3, 4, 4]
Intersection: [3, 6, 2]

'''

 



answered Sep 28 by avibootz
...