Python Practice › Set Programs › Program 22

Cartesian product of two sets

EasySet Programs · 22 of 48

Write a Python program to find the cartesian product of two sets.

Advertisement
Input
{1, 2}, {"a", "b"}
Output
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

Approach

  1. itertools.product; sort for a stable display.

Solution

Python
from itertools import productprint(sorted(product({1, 2}, {"a", "b"})))
Output
[(1, 'a'), (1, 'b'), (2, 'a'), (2, 'b')]

Learn the concept

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

More set programs

← All 48 Set Programs

Leave a Comment