Common tuples ignoring order
MediumTuple Programs · 64 of 70
Write a Python program to find the tuples that appear in both lists, treating (3, 9) and (9, 3) as the same.
InputA = [(1, 5), (4, 8), (3, 9)], B = [(9, 3), (5, 6), (5, 1), (0, 4)]
Approach
- Compare sorted versions of each tuple.
Solution
Python
A = [(1, 5), (4, 8), (3, 9)]B = [(9, 3), (5, 6), (5, 1), (0, 4)]norm_b = {tuple(sorted(t)) for t in B}print({t for t in A if tuple(sorted(t)) in norm_b})
Line by line
Line 3Sorting each tuple makes (9, 3) and (3, 9) identical.
Learn the concept
New to this topic? Read the lesson, then come back.
More tuple programs
← All 70 Tuple Programs