Python - Sets and Dictionaries Comprehension:if and nest

Introduction

Set and dictionary comprehensions support nesting and if clauses.

The following code collect squares of even items in a range:

Demo

d= [x * x for x in range(10) if x % 2 == 0]           # Lists are ordered 
print( d )
d= {x * x for x in range(10) if x % 2 == 0}           # But sets are not 
print( d )
d= {x: x * x for x in range(10) if x % 2 == 0}        # Neither are dict keys 
print( d )

Result

For nesting

Demo

d= [x + y for x in [1, 2, 3] for y in [4, 5, 6]]      # Lists keep duplicates 
print( d )
d= {x + y for x in [1, 2, 3] for y in [4, 5, 6]}      # But sets do not 
print( d )
d= {x: y for x in [1, 2, 3] for y in [4, 5, 6]}       # Neither do dict keys 
print( d )

Result

Related Topic