What is set comprehension in Python3 and why is it so handy?

with handy code snippets too!

Tech Notes
3 min readNov 1, 2023

What is Set Comprehension?

Set comprehension in Python is a compact way to process all or part of the elements in a collection to create a set. Similar to list comprehensions, set comprehensions allow us to transform one set or any iterable into a new set.

A set can be handy to use instead of a list because it guarantees that there are no duplicates in the set.

Syntax:

The basic syntax of a set comprehension is:

Where:

  • expression is the value that will be included in the new set
  • item represents each element that is drawn form the iterable
  • iterable is a collection of elements that we want to iterate over (such as lists, sets, tuples, etc)
  • condition is optional; it’s a filter that allows us to include only elements that meet certain criteria

Example

# using set comprehension to create a set of squares from 0 to 9
squares = {x**2 for x in range(10)}
print(squares) # Output: {0, 1, 4, 9, 16, 25, 36, 49, 64, 81}

In this example, x**2 is the expression that will be the element of the new set, x is the item taken from the iterable range(10), and there's no condition, so all elements are processed.

--

--