Teks sumber — English
Terjemahan — Bahasa Indonesia
``{}`` (curly braces): :ref:`dictionary <dict>` and :ref:`set <set>` displays.
For constructing builtin containers (lists, sets, tuples or dictionaries), Python provides special syntax called :dfn:`displays`. There are subtle differences between the four kinds of displays, detailed in the following sections. All displays, however, consist of comma-separated items enclosed in paired delimiters.
In list, tuple and dictionary (but not set) displays, the series may be empty::
For tuple, list and set (but not dict) displays, any item in the display may be prefixed with an asterisk (``*``). This denotes :ref:`iterable unpacking <iterable-unpacking>`. At runtime, the asterisk-prefixed expression must evaluate to an iterable, whose contents are inserted into the container at the location of the unpacking. For example::
A more advanced form of displays are :dfn:`comprehensions`, where items are computed via a set of looping and filtering instructions. See the :ref:`comprehensions` section for details.
Set displays
A :dfn:`set display` is a *non-empty* series of expressions enclosed in curly braces. For example::
>>> {"one", "two", "three"}
{'one', 'three', 'two'}
>>> {"one"} # One-element set
{'one'}
There is no special syntax for the empty set. The ``{}`` literal is a :ref:`dictionary display <dict>` that constructs an empty dictionary. Call :class:`set() <set>` with no arguments to get an empty set.
The formal grammar for set displays is:
Instead of a key-value pair, a dict item may be an expression prefixed by a double asterisk ``**``. This denotes :dfn:`dictionary unpacking`. At runtime, the expression must evaluate to a :term:`mapping`; each item of the mapping is added to the new dictionary. As with key-value pairs, later values replace values already set by earlier items and unpackings. This may be used to override a set of defaults::
List, set and dictionary :dfn:`comprehensions` are a form of :ref:`container displays <displays>` where items are computed via a set of looping and filtering instructions rather than listed explicitly.
Set comprehensions work similarly. For example, here is a set of lowercase letters::
def make_lowercase_set(iterable):
result = set()
for x in iterable:
result.add(x.lower())
return result
make_lowercase_set(['a', 'A', 'b', 'C'])
If the expression of a list or set comprehension is starred, the result will be :ref:`unpacked <iterable-unpacking>` to produce zero or more elements.
>>> system_defaults = {'color': 'blue', 'count': 8}
>>> user_defaults = {'color': 'yellow'}
>>> overrides = {'count': 5}
>>> configuration_sets = [system_defaults, user_defaults, overrides]
>>> {**d for d in configuration_sets}
{'color': 'yellow', 'count': 5}
When the underlying iterator is complete, the :attr:`~StopIteration.value` attribute of the raised :exc:`StopIteration` instance becomes the value of the yield expression. It can be either set explicitly when raising :exc:`StopIteration`, or automatically when the subiterator is a generator (by returning a value from the subgenerator).
To handle finalization when an asynchronous generator is about to be garbage collected, an event loop should define a *finalizer* function which takes an asynchronous generator-iterator and schedules the awaitable returned by :meth:`~agen.aclose`. This *finalizer* may be registered by calling :func:`sys.set_asyncgen_hooks`. When first iterated over, an asynchronous generator-iterator will store the registered *finalizer* to be called upon finalization. For a reference example of a *finalizer* method see the implementation of ``asyncio.BaseEventLoop._asyncgen_finalizer_hook`` in :source:`Lib/asyncio/base_events.py`.
Subscriptions may also be used as targets in :ref:`assignment <assignment>` or :ref:`deletion <del>` statements. In these cases, the interpreter will call the subscripted object's :meth:`~object.__setitem__` or :meth:`~object.__delitem__` :term:`special method`, respectively, instead of :meth:`~object.__getitem__`.
>>> colors = ['red', 'blue', 'green', 'black']
>>> colors[3] = 'white' # Setting item at index
>>> colors
['red', 'blue', 'green', 'white']
>>> del colors[3] # Deleting item at index 3
>>> colors
['red', 'blue', 'green']
An implementation may provide built-in functions whose positional parameters do not have names, even if they are 'named' for the purpose of documentation, and which therefore cannot be supplied by keyword. In CPython, this is the case for functions implemented in C that use :c:func:`PyArg_ParseTuple` to parse their arguments.
Sets (instances of :class:`set` or :class:`frozenset`) can be compared within and across their types.
They define order comparison operators to mean subset and superset tests. Those relations do not define total orderings (for example, the two sets ``{1,2}`` and ``{2,3}`` are not equal, nor subsets of one another, nor supersets of one another). Accordingly, sets are not appropriate arguments for functions which depend on total ordering (for example, :func:`min`, :func:`max`, and :func:`sorted` produce undefined results given a list of sets as inputs).
Comparison of sets enforces reflexivity of its elements.
The last two expressions apply to totally ordered collections (e.g. to sequences, but not to sets or mappings). See also the :deco:`~functools.total_ordering` decorator.
The operators :keyword:`in` and :keyword:`not in` test for membership. ``x in s`` evaluates to ``True`` if *x* is a member of *s*, and ``False`` otherwise. ``x not in s`` returns the negation of ``x in s``. All built-in sequences and set types support this as well as dictionary, for which :keyword:`!in` tests whether the dictionary has a given key. For container types such as list, tuple, set, frozenset, dict, or collections.deque, the expression ``x in y`` is equivalent to ``any(x is e or x == e for e in y)``.
In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: ``False``, ``None``, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a :meth:`~object.__bool__` method.
Except when part of a list or set display, an expression list containing at least one comma yields a tuple. The length of the tuple is the number of expressions in the list. The expressions are evaluated from left to right.
In an expression list or tuple, list or set display, any expression may be prefixed with an asterisk (``*``). This denotes :dfn:`iterable unpacking`.
At runtime, the asterisk-prefixed expression must evaluate to an :term:`iterable`. The iterable is expanded into a sequence of items, which are included in the new tuple, list, or set, at the site of the unpacking.
Binding or parenthesized expression, list display, dictionary display, set display
set
set
set expression