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

with handy code snippets too!

Tech Notes


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.


The basic syntax of a set comprehension is:


  • 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


# 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.

Set comprehensions are a concise and readable way to create sets, especially useful when the alternative is multiple lines of loops and conditionals.

If I had used [] instead of {} would that be list comprehension?

Yes, if you use square brackets [] instead of curly braces {}, you would be using a list comprehension instead of a set comprehension. List comprehensions allow for the creation of lists in a similar way to set comprehensions but will maintain the order of the elements and include duplicate values if they occur.

Here’s the previous example modified to use list comprehension:

# Using list comprehension to create a list 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 case, squares will be a list of the squares of numbers from 0 to 9, including…