Intersection of Two Lists Preserving Order in Python

This code returns the common elements between two lists while preserving the order they appear in the first list, filtering out duplicates.

Easy Python 3.9+ Aug 9, 2026 Lists & loops 15 views 0 copies

Python code

24 lines
Python 3.9+
def intersection_preserving_order(list1, list2):
    """
    Return the intersection of two lists while preserving the order
    of elements as they appear in list1.
    """
    set2 = set(list2)
    result = []
    seen = set()
    
    for item in list1:
        if item in set2 and item not in seen:
            result.append(item)
            seen.add(item)
    
    return result


if __name__ == "__main__":
    # Example usage
    a = [1, 2, 3, 4, 5, 3, 2]
    b = [4, 2, 6, 2, 8, 1]
    
    intersection = intersection_preserving_order(a, b)
    print(intersection)

Output

stdout
[1, 2, 4]

How it works

The function converts list2 into a set for O(1) membership checks. It then iterates over list1, and for each item that is in set2 and has not been seen before, it appends the item to the result and adds it to a seen set. The seen set prevents duplicate entries in the intersection, ensuring each common element appears only once. This approach preserves the original order from list1 because iteration follows its sequence.

Common mistakes

  • Forgetting to remove duplicates, resulting in repeated elements like [1, 2, 4, 2]
  • Using `set(list1) & set(list2)` which loses the original order
  • Not considering that sets are unordered when converting the result back to a list

Variations

  1. Use a list comprehension with a seen set for a more concise version: `[item for item in list1 if item in set2 and not (item in seen or seen.add(item))]`.
  2. If duplicates are acceptable, skip the `seen` set entirely.

Real-world use cases

  • Merging user permissions from two sources while keeping the priority order of the primary list.
  • Filtering a playlist to only songs that also appear in a liked list, preserving the playlist order.
  • Finding common tags between two posts but showing them in the original post's tag order for UI display.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Lists & loops

Related tutorials and quizzes for this topic.