Set and Dictionary Comprehension

Learn about the usage of set and dictionary comprehensions in Python.

Set comprehension

Like list comprehensions, set comprehensions offer an easy way of creating sets. It consists of braces {} that contain an expression, followed by a for clause and zero or more for or if clauses.

The general form of a set comprehension is:

s = {expression for var in sequence [optional for and/or if]}

Examples of set comprehension are shown below:

Get hands-on with 1200+ tech skills courses.