Set abstraction in Python

Introduction

Set Comprehension is a set abstraction.

Similar to List Comprehension but it creates a set, not a list.

Basic syntax

Instead of creating an empty set and adding each element at the end, you simply define the set and its contents at the same time, following this format:

new_set = {expression for member in iterable}

{ expr(item) for item in iterable }

Example

>>> from math import factorial >>> s = {len(str(factorial(x))) for x in range(20)} >>> type(s)

<class 'set'>

>>> print(s)

{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 18}

Multiple sources/conditions

# Multi-input Set Comprehension c = {x * y for x in range(5) for y in range(5)} print(c)

{0, 1, 2, 3, 4, 6, 8, 9, 12, 16}

Article author: Andrei Olegovich