Teks sumber — English
Terjemahan — Bahasa Indonesia
A comparison between numbers of different types behaves as though the exact values of those numbers were being compared. [2]_
The default values can be used to conveniently turn an integer into a single byte object::
Added default argument values for ``length`` and ``byteorder``.
The particular values ``sys.hash_info.inf`` and ``-sys.hash_info.inf`` are used as hash values for positive infinity or negative infinity (respectively).
For a :class:`complex` number ``z``, the hash values of the real and imaginary parts are combined by computing ``hash(z.real) + sys.hash_info.imag * hash(z.imag)``, reduced modulo ``2**sys.hash_info.width`` so that it lies in ``range(-2**(sys.hash_info.width - 1), 2**(sys.hash_info.width - 1))``. Again, if the result is ``-1``, it's replaced with ``-2``.
Booleans represent truth values. The :class:`bool` type has exactly two constant instances: ``True`` and ``False``.
Forward and reversed iterators over mutable sequences access values using an index. That index will continue to march forward (or backward) even if the underlying sequence is mutated. The iterator terminates only when an :exc:`IndexError` or a :exc:`StopIteration` is encountered (or when the index drops below zero).
Values of *n* less than ``0`` are treated as ``0`` (which yields an empty sequence of the same type as *s*). Note that items in the sequence *s* are not copied; they are referenced multiple times. This often haunts new Python programmers; consider::
The slice of *s* from *i* to *j* with step *k* is defined as the sequence of items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words, the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when *j* is reached (but never including *j*). When *k* is positive, *i* and *j* are reduced to ``len(s)`` if they are greater. When *k* is negative, *i* and *j* are reduced to ``len(s) - 1`` if they are greater. If *i* or *j* are omitted or ``None``, they become "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero. If *k* is ``None``, it is treated like ``1``.
Attempting to hash an immutable sequence that contains unhashable values will result in :exc:`TypeError`.
The value *n* is an integer, or an object implementing :meth:`~object.__index__`. Zero and negative values of *n* clear the sequence. Items in the sequence are not copied; they are referenced multiple times, as explained for ``s * n`` under :ref:`typesseq-common`.
Ranges containing absolute values larger than :data:`sys.maxsize` are permitted but some features (such as :func:`len`) may raise :exc:`OverflowError`.
The advantage of the :class:`range` type over a regular :class:`list` or :class:`tuple` is that a :class:`range` object will always take the same (small) amount of memory, no matter the size of the range it represents (as it only stores the ``start``, ``stop`` and ``step`` values, calculating individual items and subranges as needed).
Testing range objects for equality with ``==`` and ``!=`` compares them as sequences. That is, two range objects are considered equal if they represent the same sequence of values. (Note that two range objects that compare equal might have different :attr:`~range.start`, :attr:`~range.stop` and :attr:`~range.step` attributes, for example ``range(0) == range(2, 1, 3)`` or ``range(0, 3, 2) == range(0, 4, 2)``.)
Define '==' and '!=' to compare range objects based on the sequence of values they define (instead of comparing based on object identity).
*encoding* defaults to ``'utf-8'``; see :ref:`standard-encodings` for possible values.
*errors* controls how encoding errors are handled. If ``'strict'`` (the default), a :exc:`UnicodeError` exception is raised. Other possible values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``, ``'backslashreplace'`` and any other name registered via :func:`codecs.register_error`. See :ref:`error-handlers` for details.
Return a string which is the concatenation of the strings in *iterable*. A :exc:`TypeError` will be raised if there are any non-string values in *iterable*, including :class:`bytes` objects. The separator between elements is the string providing this method. For example:
Return a copy of the string with leading characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix; rather, all combinations of its values are stripped::
Return a copy of the string with trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* argument is not a suffix; rather, all combinations of its values are stripped. For example:
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or ``None``, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped.
The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end.
String objects have one unique built-in operation: the ``%`` operator (modulo). This is also known as the string *formatting* or *interpolation* operator. Given ``format % values`` (where *format* is a string), ``%`` conversion specifications in *format* are replaced with zero or more elements of *values*. The effect is similar to using the :c:func:`sprintf` function in the C language. For example:
If *format* requires a single argument, *values* may be a single non-tuple object. [5]_ Otherwise, *values* must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary).
Minimum field width (optional). If specified as an ``'*'`` (asterisk), the actual width is read from the next element of the tuple in *values*, and the object to convert comes after the minimum field width and optional precision.
Precision (optional), given as a ``'.'`` (dot) followed by the precision. If specified as ``'*'`` (an asterisk), the actual precision is read from the next element of the tuple in *values*, and the value to convert comes after the precision.
The conversion will be zero padded for numeric values.
The :mod:`array` module supports efficient storage of basic data types like 32-bit integers and IEEE754 double-precision floating values.
Only ASCII characters are permitted in bytes literals (regardless of the declared source code encoding). Any binary values over 127 must be entered into bytes literals using the appropriate escape sequence.
If you want to make the hex string easier to read, you can specify a single character separator *sep* parameter to include in the output. By default, this separator will be included between each byte. A second optional *bytes_per_sep* parameter controls the spacing. Positive values calculate the separator position from the right, negative values from the left.
*errors* controls how decoding errors are handled. If ``'strict'`` (the default), a :exc:`UnicodeError` exception is raised. Other possible values are ``'ignore'``, ``'replace'``, and any other name registered via :func:`codecs.register_error`. See :ref:`error-handlers` for details.
Return a bytes or bytearray object which is the concatenation of the binary data sequences in *iterable*. A :exc:`TypeError` will be raised if there are any values in *iterable* that are not :term:`bytes-like objects <bytes-like object>`, including :class:`str` objects. The separator between elements is the contents of the bytes or bytearray object providing this method.
Return a copy of the sequence with specified leading bytes removed. The *bytes* argument is a binary sequence specifying the set of byte values to be removed. If omitted or ``None``, the *bytes* argument defaults to removing :meth:`ASCII whitespace <bytes.isspace>`. The *bytes* argument is not a prefix; rather, all combinations of its values are stripped::
The binary sequence of byte values to remove may be any :term:`bytes-like object`. See :meth:`~bytes.removeprefix` for a method that will remove a single prefix string rather than all of a set of characters. For example::
Return a copy of the sequence with specified trailing bytes removed. The *bytes* argument is a binary sequence specifying the set of byte values to be removed. If omitted or ``None``, the *bytes* argument defaults to removing :meth:`ASCII whitespace <bytes.isspace>`. The *bytes* argument is not a suffix; rather, all combinations of its values are stripped::
The binary sequence of byte values to remove may be any :term:`bytes-like object`. See :meth:`~bytes.removesuffix` for a method that will remove a single suffix string rather than all of a set of characters. For example::
Return a copy of the sequence with specified leading and trailing bytes removed. The *bytes* argument is a binary sequence specifying the set of byte values to be removed. If omitted or ``None``, the *bytes* argument defaults to removing :meth:`ASCII whitespace <bytes.isspace>`. The *bytes* argument is not a prefix or suffix; rather, all combinations of its values are stripped::
The binary sequence of byte values to remove may be any :term:`bytes-like object`.
Return a copy of the sequence with each byte interpreted as an ASCII character, and the first byte capitalized and the rest lowercased. Non-ASCII byte values are passed through unchanged.
Return ``True`` if all bytes in the sequence are alphabetical ASCII characters or ASCII decimal digits and the sequence is not empty, ``False`` otherwise. Alphabetic ASCII characters are those byte values in the sequence ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``. ASCII decimal digits are those byte values in the sequence ``b'0123456789'``.
Return ``True`` if all bytes in the sequence are alphabetic ASCII characters and the sequence is not empty, ``False`` otherwise. Alphabetic ASCII characters are those byte values in the sequence ``b'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
Return ``True`` if all bytes in the sequence are ASCII decimal digits and the sequence is not empty, ``False`` otherwise. ASCII decimal digits are those byte values in the sequence ``b'0123456789'``.
Lowercase ASCII characters are those byte values in the sequence ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``.
Return ``True`` if all bytes in the sequence are ASCII whitespace and the sequence is not empty, ``False`` otherwise. ASCII whitespace characters are those byte values in the sequence ``b' \t\n\r\x0b\f'`` (space, tab, newline, carriage return, vertical tab, form feed).
Return a titlecased version of the binary sequence where words start with an uppercase ASCII character and the remaining characters are lowercase. Uncased byte values are left unmodified.
Lowercase ASCII characters are those byte values in the sequence ``b'abcdefghijklmnopqrstuvwxyz'``. Uppercase ASCII characters are those byte values in the sequence ``b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'``. All other byte values are uncased.
Bytes objects (``bytes``/``bytearray``) have one unique built-in operation: the ``%`` operator (modulo). This is also known as the bytes *formatting* or *interpolation* operator. Given ``format % values`` (where *format* is a bytes object), ``%`` conversion specifications in *format* are replaced with zero or more elements of *values*. The effect is similar to using the :c:func:`sprintf` function in the C language.
If *format* requires a single argument, *values* may be a single non-tuple object. [5]_ Otherwise, *values* must be a tuple with exactly the number of items specified by the format bytes object, or a single mapping object (for example, a dictionary).
A memoryview and a :pep:`3118` exporter are equal if their shapes are equivalent and if all corresponding values are equal when the operands' respective format codes are interpreted using :mod:`struct` syntax.
A :term:`mapping` object maps :term:`hashable` values to arbitrary objects. There are currently two standard mapping types, the :dfn:`dictionary` and :class:`frozendict`. (For other containers see the built-in :class:`list`, :class:`set`, and :class:`tuple` classes, and the :mod:`collections` module.) See :ref:`time-complexity` for the costs of the various dictionary operations.
A dictionary's keys are *almost* arbitrary values. Values that are not :term:`hashable`, that is, values containing lists, dictionaries or other mutable types (that are compared by value rather than by object identity) may not be used as keys. Values that compare equal (such as ``1``, ``1.0``, and ``True``) can be used interchangeably to index the same dictionary entry.
If keyword arguments are given, the keyword arguments and their values are added to the dictionary created from the positional argument. If a key being added is already present, the value from the keyword argument replaces the value from the positional argument.
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(d)
['one', 'two', 'three', 'four']
>>> list(d.values())
[1, 2, 3, 4]
>>> d["one"] = 42
>>> d
{'one': 42, 'two': 2, 'three': 3, 'four': 4}
>>> del d["two"]
>>> d["two"] = None
>>> d
{'one': 42, 'three': 3, 'four': 4, 'two': None}
Dictionaries are :ref:`generic <generics>` over two types, signifying (respectively) the types of the dictionary's keys and values.
Create a new dictionary with keys from *iterable* and values set to *value*.
:meth:`fromkeys` is a class method that returns a new dictionary. *value* defaults to ``None``. All of the values refer to just a single instance, so it generally doesn't make sense for *value* to be a mutable object such as an empty list. To get distinct values, use a :ref:`dict comprehension <dict>` instead.
Return a new view of the dictionary's values. See the :ref:`documentation of view objects <dict-views>`.
An equality comparison between two distinct ``dict.values()`` views will always return ``False``, even for views of the same dictionary::
>>> d = {'a': 1}
>>> d.values() == d.values()
False
Create a new dictionary with the merged keys and values of *d* and *other*, which must both be dictionaries. The values of *other* take priority when *d* and *other* share keys.
Update the dictionary *d* with keys and values from *other*, which may be either a :term:`mapping` or an :term:`iterable` of key/value pairs. The values of *other* take priority when *d* and *other* share keys.
>>> d = {"one": 1, "two": 2, "three": 3, "four": 4}
>>> d
{'one': 1, 'two': 2, 'three': 3, 'four': 4}
>>> list(reversed(d))
['four', 'three', 'two', 'one']
>>> list(reversed(d.values()))
[4, 3, 2, 1]
>>> list(reversed(d.items()))
[('four', 4), ('three', 3), ('two', 2), ('one', 1)]
The objects returned by :meth:`dict.keys`, :meth:`dict.values` and :meth:`dict.items` are *view objects*. They provide a dynamic view on the dictionary's entries, which means that when the dictionary changes, the view reflects these changes.
Return an iterator over the keys, values or items (represented as tuples of ``(key, value)``) in the dictionary.
Keys and values are iterated over in insertion order. This allows the creation of ``(value, key)`` pairs using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.
Return ``True`` if *x* is in the underlying dictionary's keys, values or items (in the latter case, *x* should be a ``(key, value)`` tuple).
Return a reverse iterator over the keys, values or items of the dictionary. The view will be iterated in reverse order of the insertion.
Keys views are set-like since their entries are unique and :term:`hashable`. Items views also have set-like operations since the (key, value) pairs are unique and the keys are hashable. If all values in an items view are hashable as well, then the items view can interoperate with other sets. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class :class:`collections.abc.Set` are available (for example, ``==``, ``<``, or ``^``). While using set operators, set-like views accept any iterable as the other operand, unlike sets which only accept sets as the input.
>>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
>>> keys = dishes.keys()
>>> values = dishes.values()
>>> # iteration
>>> n = 0
>>> for val in values:
... n += val
...
>>> print(n)
504
>>> # keys and values are iterated over in the same order (insertion order)
>>> list(keys)
['eggs', 'sausage', 'bacon', 'spam']
>>> list(values)
[2, 1, 1, 500]
>>> # view objects are dynamic and reflect dict changes
>>> del dishes['eggs']
>>> del dishes['sausage']
>>> list(keys)
['bacon', 'spam']
>>> # set operations
>>> keys & {'eggs', 'bacon', 'salad'}
{'bacon'}
>>> keys ^ {'sausage', 'juice'} == {'juice', 'sausage', 'bacon', 'spam'}
True
>>> keys | ['juice', 'juice', 'juice'] == {'bacon', 'spam', 'juice'}
True
>>> # get back a read-only proxy for the original dictionary
>>> values.mapping
mappingproxy({'bacon': 1, 'spam': 500})
>>> values.mapping['spam']
500
A :class:`!frozendict` can be hashed with ``hash(frozendict)`` if all keys and values can be hashed.
Like dictionaries, frozendicts are :ref:`generic <generics>` over two types, signifying (respectively) the types of the frozendict's keys and values.
If ``x = re.search('foo', 'foo')``, ``x`` will be a :ref:`re.Match <match-objects>` object where the return values of ``x.group(0)`` and ``x[0]`` will both be of type :class:`str`. We can represent this kind of object in type annotations with the ``GenericAlias`` ``re.Match[str]``.
If ``y = re.search(b'bar', b'bar')``, (note the ``b`` for :class:`bytes`), ``y`` will also be an instance of ``re.Match``, but the return values of ``y.group(0)`` and ``y[0]`` will both be of type :class:`bytes`. In type annotations, we would represent this variety of :ref:`re.Match <match-objects>` objects with ``re.Match[bytes]``.
def average(values: list[float]) -> float:
return sum(values) / len(values)
Another example for :term:`mapping` objects, using a :class:`dict`, which is a generic type expecting two type parameters representing the key type and the value type. In this example, the function expects a ``dict`` with keys of type :class:`str` and values of type :class:`int`::
:class:`collections.abc.ValuesView`
values
nilai