Skip to main content

Python Set Comprehension

Python Sets are datatypes in Python which allows us to store data in an unordered collection of elements.

This chapter will discuss the Set Comprehension.

What is Set Comprehension in Python?

Set Comprehension is an elegant and concise way to create a new Set from an existing Set in Python.

For example, make a set with each element multiplied by 10:

mult = {10 * x for x in range(10)}
print(mult) # {0, 70, 40, 10, 80, 50, 20, 90, 60, 30}

and this code is equivalent to:

mult = set()
for x in range(10):
mult.add(10 * x)
print(mult)

How to use Set Comprehension

The syntax for Set comprehension is:

new_set = {expression for item in iterable if condition}

where:

  • The expression is the current item in the iteration, but it is also the result, which can be manipulated before it ends up as a set item in the new set
  • The iterable can be any iterable object, like a list, tuple, set etc.
  • The condition is like a filter that only accepts the items that valuate to True.
note

The return value is a new set, leaving the old set unchanged.

Conditionals in Set Comprehension

You can add one or more conditions to the Set Comprehension.

If Conditional Set Comprehension

Example with only one if in the set comprehension, where the new set will be populated only with even numbers.

numbers = {x for x in range(20) if x % 2 == 0}
print(numbers)

Output

{0, 2, 4, 6, 8, 10, 12, 14, 16, 18}

Multiple if Conditional Set Comprehension

Example with multiple if in Set comprehension where only elements divisible by 2 and 5 are added to the new Set:

numbers = {y for y in range(100) if y % 2 == 0 if y % 5 == 0}
print(numbers)

Output

{0, 10, 20, 30, 40, 50, 60, 70, 80, 90}
note

Multiple if in the Set Comprehension are equivalent to and operation where both conditions have to be true.

if-else Conditional Set Comprehension

Example with if-else in List Comprehension where elements divisible by 2 have the value even while others have the value odd.

numbers = {i if i%2==0 else i+1 for i in range(10)}
print(numbers)

Output

{0, 2, 4, 6, 8, 10}
note

if-else in the List Comprehension are equivalent to if-else flow control.