Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 9236a4e

Browse files
committed
python#16470: mention set and dict comprehension in the tutorial. Patch by Yongzhi Pan.
1 parent f34e4de commit 9236a4e

1 file changed

Lines changed: 19 additions & 8 deletions

File tree

Doc/tutorial/datastructures.rst

Lines changed: 19 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -229,6 +229,7 @@ Don't use this example's definition of :func:`sum`: since summing numbers is
229229
such a common need, a built-in function ``sum(sequence)`` is already provided,
230230
and works exactly like this.
231231

232+
.. _tut-listcomps:
232233

233234
List Comprehensions
234235
-------------------
@@ -485,6 +486,10 @@ with no duplicate elements. Basic uses include membership testing and
485486
eliminating duplicate entries. Set objects also support mathematical operations
486487
like 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+
488493
Here 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

578589
When the keys are simple strings, it is sometimes easier to specify pairs using
579590
keyword arguments::

0 commit comments

Comments
 (0)