Python - Set and dictionary comprehensions

Introduction

Comprehensions and generators can be used with : set and dictionary comprehensions.

Demo

d = [x * x for x in range(10)]            # List comprehension: builds list 
print( d )
d = (x * x for x in range(10))            # Generator expression: produces items 
print( d )                                # Parens are often optional 
# ww w. j  a va 2s . c  o m
d = {x * x for x in range(10)}            # Set comprehension, 3.X and 2.7 
print( d )                                # {x, y} is a set in these versions too 

d = {x: x * x for x in range(10)}         # Dictionary comprehension, 3.X and 2.7 
print( d )

Result

Related Topic