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.
Python code
24 linesdef 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
[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
- 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))]`.
- 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
More from Lists & loops
- Check if List is Sorted Ascending in Python easy
- Compare Two Lists in Python: Common, Only in First, Only in Second easy
- Convert a List of Integers to a Comma-Separated String in Python easy
- Enumerate a Python List with a Custom Start Index easy
- Extract Data by Type from a List in Python: Numbers and Strings easy
- Find All Occurrences of an Item in a Python List easy
Keep learning
Related tutorials and quizzes for this topic.