Set Comprehension in Python

In a previous article I discussed list comprehensions. Today I will talk about set comprehensions. Set comprehensions were added to Python in version 2.7 and they are similir to List Comprehensions, the only difference is that we use curly braces instead of square brackets when making them.

A set is an un-ordered collection in which each element can only appear once. Below is an example of a set of the squares of all numbers between 0 and 10:

>>> nums = {x**2 for x in range(10)}
>>> nums
set([0, 1, 4, 81, 64, 9, 16, 49, 25, 36])
>>>