Python Practice › Tuple Programs › Program 57

Symmetrical tuples

MediumTuple Programs · 57 of 70

Write a Python program to extract the tuples whose reverse is also in the list.

Advertisement
Input
[("a", "b", "c"), ("d", "e"), ("c", "b", "a")]
Output
{('a', 'b', 'c')}

Approach

  1. Put all tuples in a set and keep those whose reverse is in it.

Solution

Python
data = [("a", "b", "c"), ("d", "e"), ("c", "b", "a")]pool = set(data)result = {t for t in data if t[::-1] in pool and t[::-1] != t and t < t[::-1]}print(result)
Output
{('a', 'b', 'c')}

Line by line

Line 3

t < t[::-1] keeps only one tuple from each symmetrical pair.

Advertisement

Learn the concept

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

More tuple programs

← All 70 Tuple Programs