Teks sumber — English
Terjemahan — Bahasa Indonesia
``[]`` (square brackets): :ref:`list displays <lists>`;
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.
For example, a *list display* is a series of expressions enclosed in square brackets::
In list, tuple and dictionary (but not set) displays, the series may be empty::
>>> [] # empty list
[]
>>> () # empty tuple
()
>>> {} # empty dictionary
{}
At runtime, when a display is evaluated, the listed items are evaluated from left to right and placed into a new container of the appropriate type.
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::
List displays
A :dfn:`list display` is a possibly empty series of expressions enclosed in square brackets. For example::
>>> ["one", "two", "three"]
['one', 'two', 'three']
>>> ["one"] # One-element list
['one']
>>> [] # empty list
[]
The formal grammar for list displays is:
To put it in other words, a tuple display is a parenthesized list of either:
Python's syntax also includes :ref:`expression lists <exprlists>`, where a comma-separated list of expressions is *not* enclosed in parentheses but evaluates to tuple.
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.
For example, a list of the first ten squares is::
At run time, a list comprehension creates a new list. The expression after :keyword:`!in` must evaluate to an :term:`iterable`. For each element of this iterable, the element is bound to the :keyword:`!for` clause's target as in a :keyword:`!for` statement, then the expression before :keyword:`!for` is evaluated with the target in scope and the result is added to the new list. Thus, the example above is roughly equivalent to defining and calling the following function::
def make_list_of_squares(iterable):
result = []
for x in iterable:
result.append(x**2)
return result
make_list_of_squares(range(10))
For example, a list of names from the :mod:`math` module that start with ``f`` is::
Generally, a comprehension's initial :keyword:`!for` clause may be followed by zero or more additional :keyword:`!for` or :keyword:`!if` clauses. For example, here is a list of names exposed by two Python modules, filtered to only include names that start with ``a``::
Aside from the iterable expression in the leftmost :keyword:`!for` clause, the comprehension is executed in a separate implicitly nested scope. This ensures that names assigned to in the target list don't "leak" into the enclosing scope. For example::
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.
This is often used for "flattening" lists, for example::
>>> students = ['Petr', 'Blaise', 'Jarka']
>>> teachers = ['Salim', 'Bartosz']
>>> lists_of_people = [students, teachers]
>>> [*people for people in lists_of_people]
['Petr', 'Blaise', 'Jarka', 'Salim', 'Bartosz']
def flatten_names(lists_of_people):
result = []
for people in lists_of_people:
result.extend(people)
return result
The syntax for :dfn:`generator expressions` is the same as for list :ref:`comprehensions <comprehensions>`, except that they are enclosed in parentheses instead of brackets. For example::
At runtime, a generator expression evaluates to a :term:`generator iterator` which yields the same values as the corresponding list comprehension::
>>> list(iterator)
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
>>> iterator = (nonexistent_value for x in range(10))
>>> iterator
<generator object <genexpr> at ...>
>>> list(iterator)
Traceback (most recent call last):
...
NameError: name 'nonexistent_value' is not defined
>>> iterator = (x * y for x in range(10) for y in nonexistent_iterable)
>>> iterator
<generator object <genexpr> at ...>
>>> list(iterator)
Traceback (most recent call last):
...
NameError: name 'nonexistent_iterable' is not defined
When a generator function is called, it returns an iterator known as a generator. That generator then controls the execution of the generator function. The execution starts when one of the generator's methods is called. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of :token:`~python-grammar:yield_list` to the generator's caller, or ``None`` if :token:`~python-grammar:yield_list` is omitted. By suspended, we mean that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by calling one of the generator's methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If :meth:`~generator.__next__` is used (typically via either a :keyword:`for` or the :func:`next` builtin) then the result is :const:`None`. Otherwise, if :meth:`~generator.send` is used, then the result will be the value passed in to that method.
Calling one of the asynchronous generator's methods returns an :term:`awaitable` object, and the execution starts when this object is awaited on. At that time, the execution proceeds to the first yield expression, where it is suspended again, returning the value of :token:`~python-grammar:yield_list` to the awaiting coroutine. As with a generator, suspension means that all local state is retained, including the current bindings of local variables, the instruction pointer, the internal evaluation stack, and the state of any exception handling. When the execution is resumed by awaiting on the next object returned by the asynchronous generator's methods, the function can proceed exactly as if the yield expression were just another external call. The value of the yield expression after resuming depends on the method which resumed the execution. If :meth:`~agen.__anext__` is used then the result is :const:`None`. Otherwise, if :meth:`~agen.asend` is used, then the result will be the value passed in to that method.
>>> colors = ['red', 'blue', 'green', 'black']
>>> colors[3] # Subscripting a list using the index 3
'black'
>>> list[str] # Parameterizing the list type using the type argument str
list[str]
The primary must evaluate to a callable object (user-defined functions, built-in functions, methods of built-in objects, class objects, methods of class instances, and all objects having a :meth:`~object.__call__` method are callable). All argument expressions are evaluated before the call is attempted. Please refer to section :ref:`function` for the syntax of formal :term:`parameter` lists.
If keyword arguments are present, they are first converted to positional arguments, as follows. First, a list of unfilled slots is created for the formal parameters. If there are N positional arguments, they are placed in the first N slots. Next, for each keyword argument, the identifier is used to determine the corresponding slot (if the identifier is the same as the first formal parameter name, the first slot is used, and so on). If the slot is already filled, a :exc:`TypeError` exception is raised. Otherwise, the argument is placed in the slot, filling it (even if the expression is ``None``, it fills the slot). When all arguments have been processed, the slots that are still unfilled are filled with the corresponding default value from the function definition. (Default values are calculated, once, when the function is defined; thus, a mutable object such as a list or dictionary used as default value will be shared by all calls that don't specify an argument value for the corresponding slot; this should usually be avoided.) If there are any unfilled slots for which no default value is specified, a :exc:`TypeError` exception is raised. Otherwise, the list of filled slots is used as the argument list for the call.
The code block for the function is executed, passing it the argument list. The first thing the code block will do is bind the formal parameters to the arguments; this is described in section :ref:`function`. When the code block executes a :keyword:`return` statement, this specifies the return value of the function call. If execution reaches the end of the code block without executing a :keyword:`return` statement, the return value is ``None``.
The corresponding user-defined function is called, with an argument list that is one longer than the argument list of the call: the instance becomes the first argument.
The following list describes the comparison behavior of the most important built-in types.
Sequences (instances of :class:`tuple`, :class:`list`, or :class:`range`) can be compared only within each of their types, with the restriction that ranges do not support order comparison. Equality comparison across these types results in inequality, and ordering comparison across these types raises :exc:`TypeError`.
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).
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.
See section :ref:`function` for the syntax of parameter lists. Note that functions created with lambda expressions cannot contain statements or annotations.
Expression lists
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.
Iterable unpacking in expression lists, originally proposed by :pep:`448`.
Any item in an expression list may be starred. See :pep:`646`.
Binding or parenthesized expression, list display, dictionary display, set display
Due to automatic garbage-collection, free lists, and the dynamic nature of descriptors, you may notice seemingly unusual behaviour in certain uses of the :keyword:`is` operator, like those involving comparisons between instance methods, or constants. Check their documentation for more info.
in expression lists
list
list
list expression
expression list
argument list