@@ -229,6 +229,7 @@ Don't use this example's definition of :func:`sum`: since summing numbers is
229229such a common need, a built-in function ``sum(sequence) `` is already provided,
230230and works exactly like this.
231231
232+ .. _tut-listcomps :
232233
233234List Comprehensions
234235-------------------
@@ -485,6 +486,10 @@ with no duplicate elements. Basic uses include membership testing and
485486eliminating duplicate entries. Set objects also support mathematical operations
486487like union, intersection, difference, and symmetric difference.
487488
489+ Curly braces or the :func: `set ` function can be used to create sets. Note: to
490+ create an empty set you have to use ``set() ``, not ``{} ``; the latter creates an
491+ empty dictionary, a data structure that we discuss in the next section.
492+
488493Here is a brief demonstration::
489494
490495 >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana']
@@ -511,6 +516,13 @@ Here is a brief demonstration::
511516 >>> a ^ b # letters in a or b but not both
512517 set(['r', 'd', 'b', 'm', 'z', 'l'])
513518
519+ Similarly to :ref: `list comprehensions <tut-listcomps >`, set comprehensions
520+ are also supported::
521+
522+ >>> a = {x for x in 'abracadabra' if x not in 'abc'}
523+ >>> a
524+ set(['r', 'd'])
525+
514526
515527.. _tut-dictionaries :
516528
@@ -562,18 +574,17 @@ Here is a small example using a dictionary::
562574 >>> 'guido' in tel
563575 True
564576
565- The :func: `dict ` constructor builds dictionaries directly from lists of
566- key-value pairs stored as tuples. When the pairs form a pattern, list
567- comprehensions can compactly specify the key-value list. ::
577+ The :func: `dict ` constructor builds dictionaries directly from sequences of
578+ key-value pairs::
568579
569580 >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
570581 {'sape': 4139, 'jack': 4098, 'guido': 4127}
571- >>> dict([(x, x**2) for x in (2, 4, 6)]) # use a list comprehension
572- {2: 4, 4: 16, 6: 36}
573582
574- Later in the tutorial, we will learn about Generator Expressions which are even
575- better suited for the task of supplying key-values pairs to the :func: `dict `
576- constructor.
583+ In addition, dict comprehensions can be used to create dictionaries from
584+ arbitrary key and value expressions::
585+
586+ >>> {x: x**2 for x in (2, 4, 6)}
587+ {2: 4, 4: 16, 6: 36}
577588
578589When the keys are simple strings, it is sometimes easier to specify pairs using
579590keyword arguments::
0 commit comments