List comprehension vs set comprehension

Curly braces are used for both dictionary and set comprehensions. Which one is created depends on whether you supply the associated value or not, like following (3.4):

>>> a={x for x in range(3)}
>>> a
{0, 1, 2}
>>> type(a)
<class 'set'>
>>> a={x: x for x in range(3)}
>>> a
{0: 0, 1: 1, 2: 2}
>>> type(a)
<class 'dict'>

Set is an unordered, mutable collection of unrepeated elements.

In python you can use set() to build a set, for example:

set>>> set([1,1,2,3,3])
set([1, 2, 3])
>>> set([3,3,2,5,5])
set([2, 3, 5])

Or use a set comprehension, like a list comprehension but with curly braces:

>>> {x for x in [1,1,5,5,3,3]}
set([1, 3, 5])

Tags:

Python