Python Set Comprehension

python set comprehension

Python set comprehension is very similar to list comprehension. In set comprehension, curly braces are used, while in list comprehension, square brackets are used.

For example:

 

S = {num for num in range(5)} 

print(S) 

#output #{0, 1, 2, 3, 4} 

The interesting thing about set comprehension is that the resulting set from the comprehension is made of only unique items. If you don’t want duplicate items or items occurring more than once in a sequence, then list comprehension will give you that outcome. For example:

 

S = {num**2 for num in range(4)} 

print(S) 

#output #{0, 1, 4, 9} 

Cartesian product of sets

A very important application of comprehension in sets is getting the cartesian product of sets. In simple terms, a cartesian product of a set is a set comprising all the possible combinations of the items in the set.

Below is an illustration of the Cartesian product of two sets.

{a1, a2} x {b1, b2} = {a1, b1}, {a1, b2}, {a2, b1}, {a2, b2}

Let’s see how to perform the cartesian product of sets using set comprehension


S1 = {1,2,3}

S2 = {4,5,6}

P = {(x,y) for x in S1 for y in S2}

print(P)

#output

#{(2, 4), (3, 4), (1, 5), (1, 4), (2, 6), (3, 6), (1, 6), (2, 5), (3, 5)}

Cartesian product using simple iteration

The cartesian product can also be achieved using regular iteration as shown below:


S1 = {1,2,3}

S2 = {4,5,6}

P = []

for x in S1:

    for y in S2:

    P.append((x,y))

print(P)

#output

#[(1, 4), (1, 5), (1, 6), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6)]

from itertools import product

Apart from using comprehension or iteration, you can also make use of the product in the itertools module to quickly obtain the cartesian product as shown below:


from itertools import product

S1 = {1,2,3}

S2 = {4,5,6}

P = product(S1, S2)

print(set(P))



#output

#{(2, 4), (3, 4), (1, 5), (1, 4), (2, 6), (3, 6), (1, 6), (2, 5), (3, 5)}

Leave a Reply

Your email address will not be published. Required fields are marked *