Python Practice › Tuple Programs › Program 64

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.

Advertisement
Input
A = [(1, 5), (4, 8), (3, 9)], B = [(9, 3), (5, 6), (5, 1), (0, 4)]
Output
{(3, 9), (1, 5)}

Approach

  1. 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})
Output
{(3, 9), (1, 5)}

Line by line

Line 3

Sorting each tuple makes (9, 3) and (3, 9) identical.

Advertisement

Learn the concept

New to this topic? Read the lesson, then come back.

More tuple programs

← All 70 Tuple Programs