Python Practice › Tuple Programs › Program 64
Common tuples ignoring order
Write a Python program to find the tuples that appear in both lists, treating (3, 9) and (9, 3) as the same.
Input
A = [(1, 5), (4, 8), (3, 9)], B = [(9, 3), (5, 6), (5, 1), (0, 4)]
Output
{(3, 9), (1, 5)}Approach
- Compare sorted versions of each tuple.
Solution
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})Output
{(3, 9), (1, 5)}Line by line
Line 3
Sorting each tuple makes (9, 3) and (3, 9) identical.
Learn the concept
New to this topic? Read the lesson, then come back.