Python - Set Set comprehensions

Introduction

The set comprehension expression is similar in form to the list comprehension/

It is coded in curly braces instead of square brackets and runs to make a set instead of a list.

Set comprehensions run a loop and collect the result of an expression on each iteration.

A loop variable gives access to the current iteration value for use in the collection expression.

The result is a new set you create by running the code, with all the normal set behavior.

Demo

print( {x ** 2 for x in [1, 2, 3, 4]} )         # 3.X/2.7 set comprehension

Result

Here, the loop is coded on the right, and the collection expression is coded on the left (x ** 2).

The expression is saying: return a new set containing X squared, for every X in a list.

Comprehensions can iterate across other kinds of objects, such as strings.

Demo

print( {x for x in 'test'} )                    # Same as: set('test') 
print( {c * 4 for c in 'test'} )                # Set of collected expression results 
print( {c * 4 for c in 'testham'} )
S = {c * 4 for c in 'test'}
print( S & {'mmmm', 'xxxx'} )

Result

Related Topics