1 .. XXX: reference/datamodel and this have quite a few overlaps!
10 The following sections describe the standard types that are built into the
13 .. index:: pair: built-in; types
15 The principal built-in types are numerics, sequences, mappings, files, classes,
16 instances and exceptions.
18 Some operations are supported by several object types; in particular,
19 practically all objects can be compared, tested for truth value, and converted
20 to a string (with the :func:`repr` function or the slightly different
21 :func:`str` function). The latter function is implicitly used when an object is
22 written by the :func:`print` function.
34 pair: Boolean; operations
37 Any object can be tested for truth value, for use in an :keyword:`if` or
38 :keyword:`while` condition or as operand of the Boolean operations below. The
39 following values are considered false:
41 .. index:: single: None (Built-in object)
45 .. index:: single: False (Built-in object)
49 * zero of any numeric type, for example, ``0``, ``0.0``, ``0j``.
51 * any empty sequence, for example, ``''``, ``()``, ``[]``.
53 * any empty mapping, for example, ``{}``.
55 * instances of user-defined classes, if the class defines a :meth:`__bool__` or
56 :meth:`__len__` method, when that method returns the integer zero or
57 :class:`bool` value ``False``. [#]_
59 .. index:: single: true
61 All other values are considered true --- so objects of many types are always
70 Operations and built-in functions that have a Boolean result always return ``0``
71 or ``False`` for false and ``1`` or ``True`` for true, unless otherwise stated.
72 (Important exception: the Boolean operations ``or`` and ``and`` always return
73 one of their operands.)
78 Boolean Operations --- :keyword:`and`, :keyword:`or`, :keyword:`not`
79 ====================================================================
81 .. index:: pair: Boolean; operations
83 These are the Boolean operations, ordered by ascending priority:
85 +-------------+---------------------------------+-------+
86 | Operation | Result | Notes |
87 +=============+=================================+=======+
88 | ``x or y`` | if *x* is false, then *y*, else | \(1) |
90 +-------------+---------------------------------+-------+
91 | ``x and y`` | if *x* is false, then *x*, else | \(2) |
93 +-------------+---------------------------------+-------+
94 | ``not x`` | if *x* is false, then ``True``, | \(3) |
95 | | else ``False`` | |
96 +-------------+---------------------------------+-------+
106 This is a short-circuit operator, so it only evaluates the second
107 argument if the first one is :const:`False`.
110 This is a short-circuit operator, so it only evaluates the second
111 argument if the first one is :const:`True`.
114 ``not`` has a lower priority than non-Boolean operators, so ``not a == b`` is
115 interpreted as ``not (a == b)``, and ``a == not b`` is a syntax error.
123 .. index:: pair: chaining; comparisons
125 There are eight comparison operations in Python. They all have the same
126 priority (which is higher than that of the Boolean operations). Comparisons can
127 be chained arbitrarily; for example, ``x < y <= z`` is equivalent to ``x < y and
128 y <= z``, except that *y* is evaluated only once (but in both cases *z* is not
129 evaluated at all when ``x < y`` is found to be false).
132 pair: operator; comparison
142 This table summarizes the comparison operations:
144 +------------+-------------------------+
145 | Operation | Meaning |
146 +============+=========================+
147 | ``<`` | strictly less than |
148 +------------+-------------------------+
149 | ``<=`` | less than or equal |
150 +------------+-------------------------+
151 | ``>`` | strictly greater than |
152 +------------+-------------------------+
153 | ``>=`` | greater than or equal |
154 +------------+-------------------------+
156 +------------+-------------------------+
157 | ``!=`` | not equal |
158 +------------+-------------------------+
159 | ``is`` | object identity |
160 +------------+-------------------------+
161 | ``is not`` | negated object identity |
162 +------------+-------------------------+
165 pair: object; numeric
166 pair: objects; comparing
168 Objects of different types, except different numeric types, never compare equal.
169 Furthermore, some types (for example, file objects) support only a degenerate
170 notion of comparison where any two objects of that type are unequal. The ``<``,
171 ``<=``, ``>`` and ``>=`` operators will raise a :exc:`TypeError` exception when
172 any operand is a complex number, the objects are of different types that cannot
173 be compared, or other cases where there is no defined ordering.
176 single: __eq__() (instance method)
177 single: __ne__() (instance method)
178 single: __lt__() (instance method)
179 single: __le__() (instance method)
180 single: __gt__() (instance method)
181 single: __ge__() (instance method)
183 Non-identical instances of a class normally compare as non-equal unless the
184 class defines the :meth:`__eq__` method.
186 Instances of a class cannot be ordered with respect to other instances of the
187 same class, or other types of object, unless the class defines enough of the
188 methods :meth:`__lt__`, :meth:`__le__`, :meth:`__gt__`, and :meth:`__ge__` (in
189 general, :meth:`__lt__` and :meth:`__eq__` are sufficient, if you want the
190 conventional meanings of the comparison operators).
192 The behavior of the :keyword:`is` and :keyword:`is not` operators cannot be
193 customized; also they can be applied to any two objects and never raise an
200 Two more operations with the same syntactic priority, ``in`` and ``not in``, are
201 supported only by sequence types (below).
206 Numeric Types --- :class:`int`, :class:`float`, :class:`complex`
207 ================================================================
213 object: floating point
214 object: complex number
217 There are three distinct numeric types: :dfn:`integers`, :dfn:`floating
218 point numbers`, and :dfn:`complex numbers`. In addition, Booleans are a
219 subtype of integers. Integers have unlimited precision. Floating point
220 numbers are implemented using :ctype:`double` in C---all bets on their
221 precision are off unless you happen to know the machine you are working
222 with. Complex numbers have a real and imaginary part, which are each
223 implemented using :ctype:`double` in C. To extract these parts from a
224 complex number *z*, use ``z.real`` and ``z.imag``. (The standard library
225 includes additional numeric types, :mod:`fractions` that hold rationals,
226 and :mod:`decimal` that hold floating-point numbers with user-definable
230 pair: numeric; literals
231 pair: integer; literals
232 pair: floating point; literals
233 pair: complex number; literals
234 pair: hexadecimal; literals
235 pair: octal; literals
236 pair: binary; literals
238 Numbers are created by numeric literals or as the result of built-in functions
239 and operators. Unadorned integer literals (including hex, octal and binary
240 numbers) yield integers. Numeric literals containing a decimal point or an
241 exponent sign yield floating point numbers. Appending ``'j'`` or ``'J'`` to a
242 numeric literal yields an imaginary number (a complex number with a zero real
243 part) which you can add to an integer or float to get a complex number with real
252 Python fully supports mixed arithmetic: when a binary arithmetic operator has
253 operands of different numeric types, the operand with the "narrower" type is
254 widened to that of the other, where integer is narrower than floating point,
255 which is narrower than complex. Comparisons between numbers of mixed type use
256 the same rule. [#]_ The constructors :func:`int`, :func:`float`, and
257 :func:`complex` can be used to produce numbers of a specific type.
259 All numeric types (except complex) support the following operations, sorted by
260 ascending priority (operations in the same box have the same priority; all
261 numeric operations have a higher priority than comparison operations):
263 +---------------------+---------------------------------+-------+--------------------+
264 | Operation | Result | Notes | Full documentation |
265 +=====================+=================================+=======+====================+
266 | ``x + y`` | sum of *x* and *y* | | |
267 +---------------------+---------------------------------+-------+--------------------+
268 | ``x - y`` | difference of *x* and *y* | | |
269 +---------------------+---------------------------------+-------+--------------------+
270 | ``x * y`` | product of *x* and *y* | | |
271 +---------------------+---------------------------------+-------+--------------------+
272 | ``x / y`` | quotient of *x* and *y* | | |
273 +---------------------+---------------------------------+-------+--------------------+
274 | ``x // y`` | floored quotient of *x* and | \(1) | |
276 +---------------------+---------------------------------+-------+--------------------+
277 | ``x % y`` | remainder of ``x / y`` | \(2) | |
278 +---------------------+---------------------------------+-------+--------------------+
279 | ``-x`` | *x* negated | | |
280 +---------------------+---------------------------------+-------+--------------------+
281 | ``+x`` | *x* unchanged | | |
282 +---------------------+---------------------------------+-------+--------------------+
283 | ``abs(x)`` | absolute value or magnitude of | | :func:`abs` |
285 +---------------------+---------------------------------+-------+--------------------+
286 | ``int(x)`` | *x* converted to integer | \(3) | :func:`int` |
287 +---------------------+---------------------------------+-------+--------------------+
288 | ``float(x)`` | *x* converted to floating point | \(4) | :func:`float` |
289 +---------------------+---------------------------------+-------+--------------------+
290 | ``complex(re, im)`` | a complex number with real part | | :func:`complex` |
291 | | *re*, imaginary part *im*. | | |
292 | | *im* defaults to zero. | | |
293 +---------------------+---------------------------------+-------+--------------------+
294 | ``c.conjugate()`` | conjugate of the complex number | | |
296 +---------------------+---------------------------------+-------+--------------------+
297 | ``divmod(x, y)`` | the pair ``(x // y, x % y)`` | \(2) | :func:`divmod` |
298 +---------------------+---------------------------------+-------+--------------------+
299 | ``pow(x, y)`` | *x* to the power *y* | \(5) | :func:`pow` |
300 +---------------------+---------------------------------+-------+--------------------+
301 | ``x ** y`` | *x* to the power *y* | \(5) | |
302 +---------------------+---------------------------------+-------+--------------------+
305 triple: operations on; numeric; types
306 single: conjugate() (complex number method)
311 Also referred to as integer division. The resultant value is a whole
312 integer, though the result's type is not necessarily int. The result is
313 always rounded towards minus infinity: ``1//2`` is ``0``, ``(-1)//2`` is
314 ``-1``, ``1//(-2)`` is ``-1``, and ``(-1)//(-2)`` is ``0``.
317 Not for complex numbers. Instead convert to floats using :func:`abs` if
323 single: floor() (in module math)
324 single: ceil() (in module math)
325 single: trunc() (in module math)
326 pair: numeric; conversions
329 Conversion from floating point to integer may round or truncate
330 as in C; see functions :func:`floor` and :func:`ceil` in the :mod:`math` module
331 for well-defined conversions.
334 float also accepts the strings "nan" and "inf" with an optional prefix "+"
335 or "-" for Not a Number (NaN) and positive or negative infinity.
338 Python defines ``pow(0, 0)`` and ``0 ** 0`` to be ``1``, as is common for
339 programming languages.
343 All :class:`numbers.Real` types (:class:`int` and
344 :class:`float`) also include the following operations:
346 +--------------------+------------------------------------+--------+
347 | Operation | Result | Notes |
348 +====================+====================================+========+
349 | ``math.trunc(x)`` | *x* truncated to Integral | |
350 +--------------------+------------------------------------+--------+
351 | ``round(x[, n])`` | *x* rounded to n digits, | |
352 | | rounding half to even. If n is | |
353 | | omitted, it defaults to 0. | |
354 +--------------------+------------------------------------+--------+
355 | ``math.floor(x)`` | the greatest integral float <= *x* | |
356 +--------------------+------------------------------------+--------+
357 | ``math.ceil(x)`` | the least integral float >= *x* | |
358 +--------------------+------------------------------------+--------+
360 For additional numeric operations see the :mod:`math` and :mod:`cmath`
363 .. XXXJH exceptions: overflow (when? what operations?) zerodivision
368 Bit-string Operations on Integer Types
369 --------------------------------------
371 .. _bit-string-operations:
373 Integers support additional operations that make sense only for bit-strings.
374 Negative numbers are treated as their 2's complement value (this assumes a
375 sufficiently large number of bits that no overflow occurs during the operation).
377 The priorities of the binary bitwise operations are all lower than the numeric
378 operations and higher than the comparisons; the unary operation ``~`` has the
379 same priority as the other unary numeric operations (``+`` and ``-``).
381 This table lists the bit-string operations sorted in ascending priority
382 (operations in the same box have the same priority):
384 +------------+--------------------------------+----------+
385 | Operation | Result | Notes |
386 +============+================================+==========+
387 | ``x | y`` | bitwise :dfn:`or` of *x* and | |
389 +------------+--------------------------------+----------+
390 | ``x ^ y`` | bitwise :dfn:`exclusive or` of | |
392 +------------+--------------------------------+----------+
393 | ``x & y`` | bitwise :dfn:`and` of *x* and | |
395 +------------+--------------------------------+----------+
396 | ``x << n`` | *x* shifted left by *n* bits | (1)(2) |
397 +------------+--------------------------------+----------+
398 | ``x >> n`` | *x* shifted right by *n* bits | (1)(3) |
399 +------------+--------------------------------+----------+
400 | ``~x`` | the bits of *x* inverted | |
401 +------------+--------------------------------+----------+
404 triple: operations on; integer; types
405 pair: bit-string; operations
406 pair: shifting; operations
407 pair: masking; operations
412 Negative shift counts are illegal and cause a :exc:`ValueError` to be raised.
415 A left shift by *n* bits is equivalent to multiplication by ``pow(2, n)``
416 without overflow check.
419 A right shift by *n* bits is equivalent to division by ``pow(2, n)`` without
423 Additional Methods on Integer Types
424 -----------------------------------
426 .. method:: int.bit_length()
428 Return the number of bits necessary to represent an integer in binary,
429 excluding the sign and leading zeros::
437 More precisely, if ``x`` is nonzero, then ``x.bit_length()`` is the
438 unique positive integer ``k`` such that ``2**(k-1) <= abs(x) < 2**k``.
439 Equivalently, when ``abs(x)`` is small enough to have a correctly
440 rounded logarithm, then ``k = 1 + int(log(abs(x), 2))``.
441 If ``x`` is zero, then ``x.bit_length()`` returns ``0``.
445 def bit_length(self):
446 s = bin(x) # binary representation: bin(-37) --> '-0b100101'
447 s = s.lstrip('-0b') # remove leading zeros and minus sign
448 return len(s) # len('100101') --> 6
450 .. versionadded:: 3.1
453 Additional Methods on Float
454 ---------------------------
456 The float type has some additional methods.
458 .. method:: float.as_integer_ratio()
460 Return a pair of integers whose ratio is exactly equal to the
461 original float and with a positive denominator. Raises
462 :exc:`OverflowError` on infinities and a :exc:`ValueError` on
465 Two methods support conversion to
466 and from hexadecimal strings. Since Python's floats are stored
467 internally as binary numbers, converting a float to or from a
468 *decimal* string usually involves a small rounding error. In
469 contrast, hexadecimal strings allow exact representation and
470 specification of floating-point numbers. This can be useful when
471 debugging, and in numerical work.
474 .. method:: float.hex()
476 Return a representation of a floating-point number as a hexadecimal
477 string. For finite floating-point numbers, this representation
478 will always include a leading ``0x`` and a trailing ``p`` and
482 .. classmethod:: float.fromhex(s)
484 Class method to return the float represented by a hexadecimal
485 string *s*. The string *s* may have leading and trailing
489 Note that :meth:`float.hex` is an instance method, while
490 :meth:`float.fromhex` is a class method.
492 A hexadecimal string takes the form::
494 [sign] ['0x'] integer ['.' fraction] ['p' exponent]
496 where the optional ``sign`` may by either ``+`` or ``-``, ``integer``
497 and ``fraction`` are strings of hexadecimal digits, and ``exponent``
498 is a decimal integer with an optional leading sign. Case is not
499 significant, and there must be at least one hexadecimal digit in
500 either the integer or the fraction. This syntax is similar to the
501 syntax specified in section 6.4.4.2 of the C99 standard, and also to
502 the syntax used in Java 1.5 onwards. In particular, the output of
503 :meth:`float.hex` is usable as a hexadecimal floating-point literal in
504 C or Java code, and hexadecimal strings produced by C's ``%a`` format
505 character or Java's ``Double.toHexString`` are accepted by
506 :meth:`float.fromhex`.
509 Note that the exponent is written in decimal rather than hexadecimal,
510 and that it gives the power of 2 by which to multiply the coefficient.
511 For example, the hexadecimal string ``0x3.a7p10`` represents the
512 floating-point number ``(3 + 10./16 + 7./16**2) * 2.0**10``, or
515 >>> float.fromhex('0x3.a7p10')
519 Applying the reverse conversion to ``3740.0`` gives a different
520 hexadecimal string representing the same number::
522 >>> float.hex(3740.0)
523 '0x1.d380000000000p+11'
532 single: iterator protocol
533 single: protocol; iterator
534 single: sequence; iteration
535 single: container; iteration over
537 Python supports a concept of iteration over containers. This is implemented
538 using two distinct methods; these are used to allow user-defined classes to
539 support iteration. Sequences, described below in more detail, always support
540 the iteration methods.
542 One method needs to be defined for container objects to provide iteration
545 .. XXX duplicated in reference/datamodel!
547 .. method:: container.__iter__()
549 Return an iterator object. The object is required to support the iterator
550 protocol described below. If a container supports different types of
551 iteration, additional methods can be provided to specifically request
552 iterators for those iteration types. (An example of an object supporting
553 multiple forms of iteration would be a tree structure which supports both
554 breadth-first and depth-first traversal.) This method corresponds to the
555 :attr:`tp_iter` slot of the type structure for Python objects in the Python/C
558 The iterator objects themselves are required to support the following two
559 methods, which together form the :dfn:`iterator protocol`:
562 .. method:: iterator.__iter__()
564 Return the iterator object itself. This is required to allow both containers
565 and iterators to be used with the :keyword:`for` and :keyword:`in` statements.
566 This method corresponds to the :attr:`tp_iter` slot of the type structure for
567 Python objects in the Python/C API.
570 .. method:: iterator.__next__()
572 Return the next item from the container. If there are no further items, raise
573 the :exc:`StopIteration` exception. This method corresponds to the
574 :attr:`tp_iternext` slot of the type structure for Python objects in the
577 Python defines several iterator objects to support iteration over general and
578 specific sequence types, dictionaries, and other more specialized forms. The
579 specific types are not important beyond their implementation of the iterator
582 Once an iterator's :meth:`__next__` method raises :exc:`StopIteration`, it must
583 continue to do so on subsequent calls. Implementations that do not obey this
584 property are deemed broken.
592 Python's :term:`generator`\s provide a convenient way to implement the iterator
593 protocol. If a container object's :meth:`__iter__` method is implemented as a
594 generator, it will automatically return an iterator object (technically, a
595 generator object) supplying the :meth:`__iter__` and :meth:`__next__` methods.
596 More information about generators can be found in :ref:`the documentation for
597 the yield expression <yieldexpr>`.
602 Sequence Types --- :class:`str`, :class:`bytes`, :class:`bytearray`, :class:`list`, :class:`tuple`, :class:`range`
603 ==================================================================================================================
605 There are six sequence types: strings, byte sequences (:class:`bytes` objects),
606 byte arrays (:class:`bytearray` objects), lists, tuples, and range objects. For
607 other containers see the built in :class:`dict` and :class:`set` classes, and
608 the :mod:`collections` module.
620 Strings contain Unicode characters. Their literals are written in single or
621 double quotes: ``'xyzzy'``, ``"frobozz"``. See :ref:`strings` for more about
622 string literals. In addition to the functionality described here, there are
623 also string-specific methods described in the :ref:`string-methods` section.
625 Bytes and bytearray objects contain single bytes -- the former is immutable
626 while the latter is a mutable sequence. Bytes objects can be constructed the
627 constructor, :func:`bytes`, and from literals; use a ``b`` prefix with normal
628 string syntax: ``b'xyzzy'``. To construct byte arrays, use the
629 :func:`bytearray` function.
633 While string objects are sequences of characters (represented by strings of
634 length 1), bytes and bytearray objects are sequences of *integers* (between 0
635 and 255), representing the ASCII value of single bytes. That means that for
636 a bytes or bytearray object *b*, ``b[0]`` will be an integer, while
637 ``b[0:1]`` will be a bytes or bytearray object of length 1. The
638 representation of bytes objects uses the literal format (``b'...'``) since it
639 is generally more useful than e.g. ``bytes([50, 19, 100])``. You can always
640 convert a bytes object into a list of integers using ``list(b)``.
642 Also, while in previous Python versions, byte strings and Unicode strings
643 could be exchanged for each other rather freely (barring encoding issues),
644 strings and bytes are now completely separate concepts. There's no implicit
645 en-/decoding if you pass and object of the wrong type. A string always
646 compares unequal to a bytes or bytearray object.
648 Lists are constructed with square brackets, separating items with commas: ``[a,
649 b, c]``. Tuples are constructed by the comma operator (not within square
650 brackets), with or without enclosing parentheses, but an empty tuple must have
651 the enclosing parentheses, such as ``a, b, c`` or ``()``. A single item tuple
652 must have a trailing comma, such as ``(d,)``.
654 Objects of type range are created using the :func:`range` function. They don't
655 support slicing, concatenation or repetition, and using ``in``, ``not in``,
656 :func:`min` or :func:`max` on them is inefficient.
658 Most sequence types support the following operations. The ``in`` and ``not in``
659 operations have the same priorities as the comparison operations. The ``+`` and
660 ``*`` operations have the same priority as the corresponding numeric operations.
661 [#]_ Additional methods are provided for :ref:`typesseq-mutable`.
663 This table lists the sequence operations sorted in ascending priority
664 (operations in the same box have the same priority). In the table, *s* and *t*
665 are sequences of the same type; *n*, *i* and *j* are integers:
667 +------------------+--------------------------------+----------+
668 | Operation | Result | Notes |
669 +==================+================================+==========+
670 | ``x in s`` | ``True`` if an item of *s* is | \(1) |
671 | | equal to *x*, else ``False`` | |
672 +------------------+--------------------------------+----------+
673 | ``x not in s`` | ``False`` if an item of *s* is | \(1) |
674 | | equal to *x*, else ``True`` | |
675 +------------------+--------------------------------+----------+
676 | ``s + t`` | the concatenation of *s* and | \(6) |
678 +------------------+--------------------------------+----------+
679 | ``s * n, n * s`` | *n* shallow copies of *s* | \(2) |
681 +------------------+--------------------------------+----------+
682 | ``s[i]`` | *i*'th item of *s*, origin 0 | \(3) |
683 +------------------+--------------------------------+----------+
684 | ``s[i:j]`` | slice of *s* from *i* to *j* | (3)(4) |
685 +------------------+--------------------------------+----------+
686 | ``s[i:j:k]`` | slice of *s* from *i* to *j* | (3)(5) |
687 | | with step *k* | |
688 +------------------+--------------------------------+----------+
689 | ``len(s)`` | length of *s* | |
690 +------------------+--------------------------------+----------+
691 | ``min(s)`` | smallest item of *s* | |
692 +------------------+--------------------------------+----------+
693 | ``max(s)`` | largest item of *s* | |
694 +------------------+--------------------------------+----------+
696 Sequence types also support comparisons. In particular, tuples and lists are
697 compared lexicographically by comparing corresponding elements. This means that
698 to compare equal, every element must compare equal and the two sequences must be
699 of the same type and have the same length. (For full details see
700 :ref:`comparisons` in the language reference.)
703 triple: operations on; sequence; types
707 pair: concatenation; operation
708 pair: repetition; operation
709 pair: subscript; operation
710 pair: slice; operation
717 When *s* is a string object, the ``in`` and ``not in`` operations act like a
721 Values of *n* less than ``0`` are treated as ``0`` (which yields an empty
722 sequence of the same type as *s*). Note also that the copies are shallow;
723 nested structures are not copied. This often haunts new Python programmers;
729 >>> lists[0].append(3)
733 What has happened is that ``[[]]`` is a one-element list containing an empty
734 list, so all three elements of ``[[]] * 3`` are (pointers to) this single empty
735 list. Modifying any of the elements of ``lists`` modifies this single list.
736 You can create a list of different lists this way:
738 >>> lists = [[] for i in range(3)]
739 >>> lists[0].append(3)
740 >>> lists[1].append(5)
741 >>> lists[2].append(7)
746 If *i* or *j* is negative, the index is relative to the end of the string:
747 ``len(s) + i`` or ``len(s) + j`` is substituted. But note that ``-0`` is
751 The slice of *s* from *i* to *j* is defined as the sequence of items with index
752 *k* such that ``i <= k < j``. If *i* or *j* is greater than ``len(s)``, use
753 ``len(s)``. If *i* is omitted or ``None``, use ``0``. If *j* is omitted or
754 ``None``, use ``len(s)``. If *i* is greater than or equal to *j*, the slice is
758 The slice of *s* from *i* to *j* with step *k* is defined as the sequence of
759 items with index ``x = i + n*k`` such that ``0 <= n < (j-i)/k``. In other words,
760 the indices are ``i``, ``i+k``, ``i+2*k``, ``i+3*k`` and so on, stopping when
761 *j* is reached (but never including *j*). If *i* or *j* is greater than
762 ``len(s)``, use ``len(s)``. If *i* or *j* are omitted or ``None``, they become
763 "end" values (which end depends on the sign of *k*). Note, *k* cannot be zero.
764 If *k* is ``None``, it is treated like ``1``.
767 If *s* and *t* are both strings, some Python implementations such as CPython can
768 usually perform an in-place optimization for assignments of the form ``s=s+t``
769 or ``s+=t``. When applicable, this optimization makes quadratic run-time much
770 less likely. This optimization is both version and implementation dependent.
771 For performance sensitive code, it is preferable to use the :meth:`str.join`
772 method which assures consistent linear concatenation performance across versions
781 .. index:: pair: string; methods
783 String objects support the methods listed below. Note that none of these
784 methods take keyword arguments.
786 In addition, Python's strings support the sequence type methods described in
787 the :ref:`typesseq` section. To output formatted strings, see the
788 :ref:`string-formatting` section. Also, see the :mod:`re` module for string
789 functions based on regular expressions.
791 .. method:: str.capitalize()
793 Return a copy of the string with only its first character capitalized.
796 .. method:: str.center(width[, fillchar])
798 Return centered in a string of length *width*. Padding is done using the
799 specified *fillchar* (default is a space).
802 .. method:: str.count(sub[, start[, end]])
804 Return the number of non-overlapping occurrences of substring *sub* in the
805 range [*start*, *end*]. Optional arguments *start* and *end* are
806 interpreted as in slice notation.
809 .. method:: str.encode([encoding[, errors]])
811 Return an encoded version of the string as a bytes object. Default encoding
812 is the current default string encoding. *errors* may be given to set a
813 different error handling scheme. The default for *errors* is ``'strict'``,
814 meaning that encoding errors raise a :exc:`UnicodeError`. Other possible
815 values are ``'ignore'``, ``'replace'``, ``'xmlcharrefreplace'``,
816 ``'backslashreplace'`` and any other name registered via
817 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
818 list of possible encodings, see section :ref:`standard-encodings`.
821 .. method:: str.endswith(suffix[, start[, end]])
823 Return ``True`` if the string ends with the specified *suffix*, otherwise return
824 ``False``. *suffix* can also be a tuple of suffixes to look for. With optional
825 *start*, test beginning at that position. With optional *end*, stop comparing
829 .. method:: str.expandtabs([tabsize])
831 Return a copy of the string where all tab characters are replaced by one or
832 more spaces, depending on the current column and the given tab size. The
833 column number is reset to zero after each newline occurring in the string.
834 If *tabsize* is not given, a tab size of ``8`` characters is assumed. This
835 doesn't understand other non-printing characters or escape sequences.
838 .. method:: str.find(sub[, start[, end]])
840 Return the lowest index in the string where substring *sub* is found, such that
841 *sub* is contained in the range [*start*, *end*]. Optional arguments *start*
842 and *end* are interpreted as in slice notation. Return ``-1`` if *sub* is not
846 .. method:: str.format(*args, **kwargs)
848 Perform a string formatting operation. The *format_string* argument can
849 contain literal text or replacement fields delimited by braces ``{}``. Each
850 replacement field contains either the numeric index of a positional argument,
851 or the name of a keyword argument. Returns a copy of *format_string* where
852 each replacement field is replaced with the string value of the corresponding
855 >>> "The sum of 1 + 2 is {0}".format(1+2)
856 'The sum of 1 + 2 is 3'
858 See :ref:`formatstrings` for a description of the various formatting options
859 that can be specified in format strings.
862 .. method:: str.index(sub[, start[, end]])
864 Like :meth:`find`, but raise :exc:`ValueError` when the substring is not found.
867 .. method:: str.isalnum()
869 Return true if all characters in the string are alphanumeric and there is at
870 least one character, false otherwise.
873 .. method:: str.isalpha()
875 Return true if all characters in the string are alphabetic and there is at least
876 one character, false otherwise.
879 .. method:: str.isdecimal()
881 Return true if all characters in the string are decimal
882 characters and there is at least one character, false
883 otherwise. Decimal characters include digit characters, and all characters
884 that that can be used to form decimal-radix numbers, e.g. U+0660,
885 ARABIC-INDIC DIGIT ZERO.
888 .. method:: str.isdigit()
890 Return true if all characters in the string are digits and there is at least one
891 character, false otherwise.
894 .. method:: str.isidentifier()
896 Return true if the string is a valid identifier according to the language
897 definition, section :ref:`identifiers`.
900 .. method:: str.islower()
902 Return true if all cased characters in the string are lowercase and there is at
903 least one cased character, false otherwise.
906 .. method:: str.isnumeric()
908 Return true if all characters in the string are numeric
909 characters, and there is at least one character, false
910 otherwise. Numeric characters include digit characters, and all characters
911 that have the Unicode numeric value property, e.g. U+2155,
912 VULGAR FRACTION ONE FIFTH.
915 .. method:: str.isprintable()
917 Return true if all characters in the string are printable or the string is
918 empty, false otherwise. Nonprintable characters are those characters defined
919 in the Unicode character database as "Other" or "Separator", excepting the
920 ASCII space (0x20) which is considered printable. (Note that printable
921 characters in this context are those which should not be escaped when
922 :func:`repr` is invoked on a string. It has no bearing on the handling of
923 strings written to :data:`sys.stdout` or :data:`sys.stderr`.)
926 .. method:: str.isspace()
928 Return true if there are only whitespace characters in the string and there is
929 at least one character, false otherwise.
932 .. method:: str.istitle()
934 Return true if the string is a titlecased string and there is at least one
935 character, for example uppercase characters may only follow uncased characters
936 and lowercase characters only cased ones. Return false otherwise.
939 .. method:: str.isupper()
941 Return true if all cased characters in the string are uppercase and there is at
942 least one cased character, false otherwise.
945 .. method:: str.join(seq)
947 Return a string which is the concatenation of the strings in the sequence
948 *seq*. A :exc:`TypeError` will be raised if there are any non-string values
949 in *seq*, including :class:`bytes` objects. The separator between elements
950 is the string providing this method.
953 .. method:: str.ljust(width[, fillchar])
955 Return the string left justified in a string of length *width*. Padding is done
956 using the specified *fillchar* (default is a space). The original string is
957 returned if *width* is less than ``len(s)``.
960 .. method:: str.lower()
962 Return a copy of the string converted to lowercase.
965 .. method:: str.lstrip([chars])
967 Return a copy of the string with leading characters removed. The *chars*
968 argument is a string specifying the set of characters to be removed. If omitted
969 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
970 argument is not a prefix; rather, all combinations of its values are stripped:
972 >>> ' spacious '.lstrip()
974 >>> 'www.example.com'.lstrip('cmowz.')
978 .. staticmethod:: str.maketrans(x[, y[, z]])
980 This static method returns a translation table usable for :meth:`str.translate`.
982 If there is only one argument, it must be a dictionary mapping Unicode
983 ordinals (integers) or characters (strings of length 1) to Unicode ordinals,
984 strings (of arbitrary lengths) or None. Character keys will then be
985 converted to ordinals.
987 If there are two arguments, they must be strings of equal length, and in the
988 resulting dictionary, each character in x will be mapped to the character at
989 the same position in y. If there is a third argument, it must be a string,
990 whose characters will be mapped to None in the result.
993 .. method:: str.partition(sep)
995 Split the string at the first occurrence of *sep*, and return a 3-tuple
996 containing the part before the separator, the separator itself, and the part
997 after the separator. If the separator is not found, return a 3-tuple containing
998 the string itself, followed by two empty strings.
1001 .. method:: str.replace(old, new[, count])
1003 Return a copy of the string with all occurrences of substring *old* replaced by
1004 *new*. If the optional argument *count* is given, only the first *count*
1005 occurrences are replaced.
1008 .. method:: str.rfind(sub[, start[, end]])
1010 Return the highest index in the string where substring *sub* is found, such that
1011 *sub* is contained within s[start,end]. Optional arguments *start* and *end*
1012 are interpreted as in slice notation. Return ``-1`` on failure.
1015 .. method:: str.rindex(sub[, start[, end]])
1017 Like :meth:`rfind` but raises :exc:`ValueError` when the substring *sub* is not
1021 .. method:: str.rjust(width[, fillchar])
1023 Return the string right justified in a string of length *width*. Padding is done
1024 using the specified *fillchar* (default is a space). The original string is
1025 returned if *width* is less than ``len(s)``.
1028 .. method:: str.rpartition(sep)
1030 Split the string at the last occurrence of *sep*, and return a 3-tuple
1031 containing the part before the separator, the separator itself, and the part
1032 after the separator. If the separator is not found, return a 3-tuple containing
1033 two empty strings, followed by the string itself.
1036 .. method:: str.rsplit([sep[, maxsplit]])
1038 Return a list of the words in the string, using *sep* as the delimiter string.
1039 If *maxsplit* is given, at most *maxsplit* splits are done, the *rightmost*
1040 ones. If *sep* is not specified or ``None``, any whitespace string is a
1041 separator. Except for splitting from the right, :meth:`rsplit` behaves like
1042 :meth:`split` which is described in detail below.
1045 .. method:: str.rstrip([chars])
1047 Return a copy of the string with trailing characters removed. The *chars*
1048 argument is a string specifying the set of characters to be removed. If omitted
1049 or ``None``, the *chars* argument defaults to removing whitespace. The *chars*
1050 argument is not a suffix; rather, all combinations of its values are stripped:
1052 >>> ' spacious '.rstrip()
1054 >>> 'mississippi'.rstrip('ipz')
1058 .. method:: str.split([sep[, maxsplit]])
1060 Return a list of the words in the string, using *sep* as the delimiter
1061 string. If *maxsplit* is given, at most *maxsplit* splits are done (thus,
1062 the list will have at most ``maxsplit+1`` elements). If *maxsplit* is not
1063 specified, then there is no limit on the number of splits (all possible
1066 If *sep* is given, consecutive delimiters are not grouped together and are
1067 deemed to delimit empty strings (for example, ``'1,,2'.split(',')`` returns
1068 ``['1', '', '2']``). The *sep* argument may consist of multiple characters
1069 (for example, ``'1<>2<>3'.split('<>')`` returns ``['1', '2', '3']``).
1070 Splitting an empty string with a specified separator returns ``['']``.
1072 If *sep* is not specified or is ``None``, a different splitting algorithm is
1073 applied: runs of consecutive whitespace are regarded as a single separator,
1074 and the result will contain no empty strings at the start or end if the
1075 string has leading or trailing whitespace. Consequently, splitting an empty
1076 string or a string consisting of just whitespace with a ``None`` separator
1079 For example, ``' 1 2 3 '.split()`` returns ``['1', '2', '3']``, and
1080 ``' 1 2 3 '.split(None, 1)`` returns ``['1', '2 3 ']``.
1083 .. method:: str.splitlines([keepends])
1085 Return a list of the lines in the string, breaking at line boundaries. Line
1086 breaks are not included in the resulting list unless *keepends* is given and
1090 .. method:: str.startswith(prefix[, start[, end]])
1092 Return ``True`` if string starts with the *prefix*, otherwise return ``False``.
1093 *prefix* can also be a tuple of prefixes to look for. With optional *start*,
1094 test string beginning at that position. With optional *end*, stop comparing
1095 string at that position.
1098 .. method:: str.strip([chars])
1100 Return a copy of the string with the leading and trailing characters removed.
1101 The *chars* argument is a string specifying the set of characters to be removed.
1102 If omitted or ``None``, the *chars* argument defaults to removing whitespace.
1103 The *chars* argument is not a prefix or suffix; rather, all combinations of its
1104 values are stripped:
1106 >>> ' spacious '.strip()
1108 >>> 'www.example.com'.strip('cmowz.')
1112 .. method:: str.swapcase()
1114 Return a copy of the string with uppercase characters converted to lowercase and
1118 .. method:: str.title()
1120 Return a titlecased version of the string: words start with uppercase
1121 characters, all remaining cased characters are lowercase.
1124 .. method:: str.translate(map)
1126 Return a copy of the *s* where all characters have been mapped through the
1127 *map* which must be a dictionary of Unicode ordinals (integers) to Unicode
1128 ordinals, strings or ``None``. Unmapped characters are left untouched.
1129 Characters mapped to ``None`` are deleted.
1131 You can use :meth:`str.maketrans` to create a translation map from
1132 character-to-character mappings in different formats.
1136 An even more flexible approach is to create a custom character mapping
1137 codec using the :mod:`codecs` module (see :mod:`encodings.cp1251` for an
1141 .. method:: str.upper()
1143 Return a copy of the string converted to uppercase.
1146 .. method:: str.zfill(width)
1148 Return the numeric string left filled with zeros in a string of length
1149 *width*. A sign prefix is handled correctly. The original string is
1150 returned if *width* is less than ``len(s)``.
1154 .. _old-string-formatting:
1156 Old String Formatting Operations
1157 --------------------------------
1160 single: formatting, string (%)
1161 single: interpolation, string (%)
1162 single: string; formatting
1163 single: string; interpolation
1164 single: printf-style formatting
1165 single: sprintf-style formatting
1166 single: % formatting
1167 single: % interpolation
1169 .. XXX is the note enough?
1173 The formatting operations described here are obsolete and may go away in future
1174 versions of Python. Use the new :ref:`string-formatting` in new code.
1176 String objects have one unique built-in operation: the ``%`` operator (modulo).
1177 This is also known as the string *formatting* or *interpolation* operator.
1178 Given ``format % values`` (where *format* is a string), ``%`` conversion
1179 specifications in *format* are replaced with zero or more elements of *values*.
1180 The effect is similar to the using :cfunc:`sprintf` in the C language.
1182 If *format* requires a single argument, *values* may be a single non-tuple
1183 object. [#]_ Otherwise, *values* must be a tuple with exactly the number of
1184 items specified by the format string, or a single mapping object (for example, a
1187 A conversion specifier contains two or more characters and has the following
1188 components, which must occur in this order:
1190 #. The ``'%'`` character, which marks the start of the specifier.
1192 #. Mapping key (optional), consisting of a parenthesised sequence of characters
1193 (for example, ``(somename)``).
1195 #. Conversion flags (optional), which affect the result of some conversion
1198 #. Minimum field width (optional). If specified as an ``'*'`` (asterisk), the
1199 actual width is read from the next element of the tuple in *values*, and the
1200 object to convert comes after the minimum field width and optional precision.
1202 #. Precision (optional), given as a ``'.'`` (dot) followed by the precision. If
1203 specified as ``'*'`` (an asterisk), the actual width is read from the next
1204 element of the tuple in *values*, and the value to convert comes after the
1207 #. Length modifier (optional).
1211 When the right argument is a dictionary (or other mapping type), then the
1212 formats in the string *must* include a parenthesised mapping key into that
1213 dictionary inserted immediately after the ``'%'`` character. The mapping key
1214 selects the value to be formatted from the mapping. For example:
1217 >>> print('%(language)s has %(#)03d quote types.' % \
1218 ... {'language': "Python", "#": 2})
1219 Python has 002 quote types.
1221 In this case no ``*`` specifiers may occur in a format (since they require a
1222 sequential parameter list).
1224 The conversion flag characters are:
1226 +---------+---------------------------------------------------------------------+
1228 +=========+=====================================================================+
1229 | ``'#'`` | The value conversion will use the "alternate form" (where defined |
1231 +---------+---------------------------------------------------------------------+
1232 | ``'0'`` | The conversion will be zero padded for numeric values. |
1233 +---------+---------------------------------------------------------------------+
1234 | ``'-'`` | The converted value is left adjusted (overrides the ``'0'`` |
1235 | | conversion if both are given). |
1236 +---------+---------------------------------------------------------------------+
1237 | ``' '`` | (a space) A blank should be left before a positive number (or empty |
1238 | | string) produced by a signed conversion. |
1239 +---------+---------------------------------------------------------------------+
1240 | ``'+'`` | A sign character (``'+'`` or ``'-'``) will precede the conversion |
1241 | | (overrides a "space" flag). |
1242 +---------+---------------------------------------------------------------------+
1244 A length modifier (``h``, ``l``, or ``L``) may be present, but is ignored as it
1245 is not necessary for Python -- so e.g. ``%ld`` is identical to ``%d``.
1247 The conversion types are:
1249 +------------+-----------------------------------------------------+-------+
1250 | Conversion | Meaning | Notes |
1251 +============+=====================================================+=======+
1252 | ``'d'`` | Signed integer decimal. | |
1253 +------------+-----------------------------------------------------+-------+
1254 | ``'i'`` | Signed integer decimal. | |
1255 +------------+-----------------------------------------------------+-------+
1256 | ``'o'`` | Signed octal value. | \(1) |
1257 +------------+-----------------------------------------------------+-------+
1258 | ``'u'`` | Obsolete type -- it is identical to ``'d'``. | \(7) |
1259 +------------+-----------------------------------------------------+-------+
1260 | ``'x'`` | Signed hexadecimal (lowercase). | \(2) |
1261 +------------+-----------------------------------------------------+-------+
1262 | ``'X'`` | Signed hexadecimal (uppercase). | \(2) |
1263 +------------+-----------------------------------------------------+-------+
1264 | ``'e'`` | Floating point exponential format (lowercase). | \(3) |
1265 +------------+-----------------------------------------------------+-------+
1266 | ``'E'`` | Floating point exponential format (uppercase). | \(3) |
1267 +------------+-----------------------------------------------------+-------+
1268 | ``'f'`` | Floating point decimal format. | \(3) |
1269 +------------+-----------------------------------------------------+-------+
1270 | ``'F'`` | Floating point decimal format. | \(3) |
1271 +------------+-----------------------------------------------------+-------+
1272 | ``'g'`` | Floating point format. Uses lowercase exponential | \(4) |
1273 | | format if exponent is less than -4 or not less than | |
1274 | | precision, decimal format otherwise. | |
1275 +------------+-----------------------------------------------------+-------+
1276 | ``'G'`` | Floating point format. Uses uppercase exponential | \(4) |
1277 | | format if exponent is less than -4 or not less than | |
1278 | | precision, decimal format otherwise. | |
1279 +------------+-----------------------------------------------------+-------+
1280 | ``'c'`` | Single character (accepts integer or single | |
1281 | | character string). | |
1282 +------------+-----------------------------------------------------+-------+
1283 | ``'r'`` | String (converts any python object using | \(5) |
1284 | | :func:`repr`). | |
1285 +------------+-----------------------------------------------------+-------+
1286 | ``'s'`` | String (converts any python object using | |
1287 | | :func:`str`). | |
1288 +------------+-----------------------------------------------------+-------+
1289 | ``'%'`` | No argument is converted, results in a ``'%'`` | |
1290 | | character in the result. | |
1291 +------------+-----------------------------------------------------+-------+
1296 The alternate form causes a leading zero (``'0'``) to be inserted between
1297 left-hand padding and the formatting of the number if the leading character
1298 of the result is not already a zero.
1301 The alternate form causes a leading ``'0x'`` or ``'0X'`` (depending on whether
1302 the ``'x'`` or ``'X'`` format was used) to be inserted between left-hand padding
1303 and the formatting of the number if the leading character of the result is not
1307 The alternate form causes the result to always contain a decimal point, even if
1308 no digits follow it.
1310 The precision determines the number of digits after the decimal point and
1314 The alternate form causes the result to always contain a decimal point, and
1315 trailing zeroes are not removed as they would otherwise be.
1317 The precision determines the number of significant digits before and after the
1318 decimal point and defaults to 6.
1321 The precision determines the maximal number of characters used.
1327 Since Python strings have an explicit length, ``%s`` conversions do not assume
1328 that ``'\0'`` is the end of the string.
1332 .. versionchanged:: 3.1
1333 ``%f`` conversions for numbers whose absolute value is over 1e50 are no
1334 longer replaced by ``%g`` conversions.
1340 Additional string operations are defined in standard modules :mod:`string` and
1349 .. index:: object: range
1351 The :class:`range` type is an immutable sequence which is commonly used for
1352 looping. The advantage of the :class:`range` type is that an :class:`range`
1353 object will always take the same amount of memory, no matter the size of the
1354 range it represents. There are no consistent performance advantages.
1356 Range objects have very little behavior: they only support indexing, iteration,
1357 and the :func:`len` function.
1360 .. _typesseq-mutable:
1362 Mutable Sequence Types
1363 ----------------------
1366 triple: mutable; sequence; types
1370 List and bytearray objects support additional operations that allow in-place
1371 modification of the object. Other mutable sequence types (when added to the
1372 language) should also support these operations. Strings and tuples are
1373 immutable sequence types: such objects cannot be modified once created. The
1374 following operations are defined on mutable sequence types (where *x* is an
1377 Note that while lists allow their items to be of any type, bytearray object
1378 "items" are all integers in the range 0 <= x < 256.
1380 +------------------------------+--------------------------------+---------------------+
1381 | Operation | Result | Notes |
1382 +==============================+================================+=====================+
1383 | ``s[i] = x`` | item *i* of *s* is replaced by | |
1385 +------------------------------+--------------------------------+---------------------+
1386 | ``s[i:j] = t`` | slice of *s* from *i* to *j* | |
1387 | | is replaced by the contents of | |
1388 | | the iterable *t* | |
1389 +------------------------------+--------------------------------+---------------------+
1390 | ``del s[i:j]`` | same as ``s[i:j] = []`` | |
1391 +------------------------------+--------------------------------+---------------------+
1392 | ``s[i:j:k] = t`` | the elements of ``s[i:j:k]`` | \(1) |
1393 | | are replaced by those of *t* | |
1394 +------------------------------+--------------------------------+---------------------+
1395 | ``del s[i:j:k]`` | removes the elements of | |
1396 | | ``s[i:j:k]`` from the list | |
1397 +------------------------------+--------------------------------+---------------------+
1398 | ``s.append(x)`` | same as ``s[len(s):len(s)] = | |
1400 +------------------------------+--------------------------------+---------------------+
1401 | ``s.extend(x)`` | same as ``s[len(s):len(s)] = | \(2) |
1403 +------------------------------+--------------------------------+---------------------+
1404 | ``s.count(x)`` | return number of *i*'s for | |
1405 | | which ``s[i] == x`` | |
1406 +------------------------------+--------------------------------+---------------------+
1407 | ``s.index(x[, i[, j]])`` | return smallest *k* such that | \(3) |
1408 | | ``s[k] == x`` and ``i <= k < | |
1410 +------------------------------+--------------------------------+---------------------+
1411 | ``s.insert(i, x)`` | same as ``s[i:i] = [x]`` | \(4) |
1412 +------------------------------+--------------------------------+---------------------+
1413 | ``s.pop([i])`` | same as ``x = s[i]; del s[i]; | \(5) |
1415 +------------------------------+--------------------------------+---------------------+
1416 | ``s.remove(x)`` | same as ``del s[s.index(x)]`` | \(3) |
1417 +------------------------------+--------------------------------+---------------------+
1418 | ``s.reverse()`` | reverses the items of *s* in | \(6) |
1420 +------------------------------+--------------------------------+---------------------+
1421 | ``s.sort([key[, reverse]])`` | sort the items of *s* in place | (6), (7), (8) |
1422 +------------------------------+--------------------------------+---------------------+
1425 triple: operations on; sequence; types
1426 triple: operations on; list; type
1427 pair: subscript; assignment
1428 pair: slice; assignment
1430 single: append() (sequence method)
1431 single: extend() (sequence method)
1432 single: count() (sequence method)
1433 single: index() (sequence method)
1434 single: insert() (sequence method)
1435 single: pop() (sequence method)
1436 single: remove() (sequence method)
1437 single: reverse() (sequence method)
1438 single: sort() (sequence method)
1443 *t* must have the same length as the slice it is replacing.
1446 *x* can be any iterable object.
1449 Raises :exc:`ValueError` when *x* is not found in *s*. When a negative index is
1450 passed as the second or third parameter to the :meth:`index` method, the sequence
1451 length is added, as for slice indices. If it is still negative, it is truncated
1452 to zero, as for slice indices.
1455 When a negative index is passed as the first parameter to the :meth:`insert`
1456 method, the sequence length is added, as for slice indices. If it is still
1457 negative, it is truncated to zero, as for slice indices.
1460 The optional argument *i* defaults to ``-1``, so that by default the last
1461 item is removed and returned.
1464 The :meth:`sort` and :meth:`reverse` methods modify the sequence in place for
1465 economy of space when sorting or reversing a large sequence. To remind you
1466 that they operate by side effect, they don't return the sorted or reversed
1470 The :meth:`sort` method takes optional arguments for controlling the
1471 comparisons. Each must be specified as a keyword argument.
1473 *key* specifies a function of one argument that is used to extract a comparison
1474 key from each list element: ``key=str.lower``. The default value is ``None``.
1476 *reverse* is a boolean value. If set to ``True``, then the list elements are
1477 sorted as if each comparison were reversed.
1479 The :meth:`sort` method is guaranteed to be stable. A
1480 sort is stable if it guarantees not to change the relative order of elements
1481 that compare equal --- this is helpful for sorting in multiple passes (for
1482 example, sort by department, then by salary grade).
1484 While a list is being sorted, the effect of attempting to mutate, or even
1485 inspect, the list is undefined. The C implementation
1486 makes the list appear empty for the duration, and raises :exc:`ValueError` if it
1487 can detect that the list has been mutated during a sort.
1490 :meth:`sort` is not supported by :class:`bytearray` objects.
1494 Bytes and Byte Array Methods
1495 ----------------------------
1497 .. index:: pair: bytes; methods
1498 pair: bytearray; methods
1500 Bytes and bytearray objects, being "strings of bytes", have all methods found on
1501 strings, with the exception of :func:`encode`, :func:`format` and
1502 :func:`isidentifier`, which do not make sense with these types. For converting
1503 the objects to strings, they have a :func:`decode` method.
1505 Wherever one of these methods needs to interpret the bytes as characters
1506 (e.g. the :func:`is...` methods), the ASCII character set is assumed.
1510 The methods on bytes and bytearray objects don't accept strings as their
1511 arguments, just as the methods on strings don't accept bytes as their
1512 arguments. For example, you have to write ::
1515 b = a.replace("a", "f")
1520 b = a.replace(b"a", b"f")
1523 .. method:: bytes.decode([encoding[, errors]])
1524 bytearray.decode([encoding[, errors]])
1526 Return a string decoded from the given bytes. Default encoding is the
1527 current default string encoding. *errors* may be given to set a different
1528 error handling scheme. The default for *errors* is ``'strict'``, meaning
1529 that encoding errors raise a :exc:`UnicodeError`. Other possible values are
1530 ``'ignore'``, ``'replace'`` and any other name registered via
1531 :func:`codecs.register_error`, see section :ref:`codec-base-classes`. For a
1532 list of possible encodings, see section :ref:`standard-encodings`.
1535 The bytes and bytearray types have an additional class method:
1537 .. classmethod:: bytes.fromhex(string)
1538 bytearray.fromhex(string)
1540 This :class:`bytes` class method returns a bytes or bytearray object,
1541 decoding the given string object. The string must contain two hexadecimal
1542 digits per byte, spaces are ignored.
1544 >>> bytes.fromhex('f0 f1f2 ')
1548 The maketrans and translate methods differ in semantics from the versions
1549 available on strings:
1551 .. method:: bytes.translate(table[, delete])
1552 bytearray.translate(table[, delete])
1554 Return a copy of the bytes or bytearray object where all bytes occurring in
1555 the optional argument *delete* are removed, and the remaining bytes have been
1556 mapped through the given translation table, which must be a bytes object of
1559 You can use the :func:`bytes.maketrans` method to create a translation table.
1561 Set the *table* argument to ``None`` for translations that only delete
1564 >>> b'read this short text'.translate(None, b'aeiou')
1568 .. staticmethod:: bytes.maketrans(from, to)
1569 bytearray.maketrans(from, to)
1571 This static method returns a translation table usable for
1572 :meth:`bytes.translate` that will map each character in *from* into the
1573 character at the same position in *to*; *from* and *to* must be bytes objects
1574 and have the same length.
1576 .. versionadded:: 3.1
1581 Set Types --- :class:`set`, :class:`frozenset`
1582 ==============================================
1584 .. index:: object: set
1586 A :dfn:`set` object is an unordered collection of distinct :term:`hashable` objects.
1587 Common uses include membership testing, removing duplicates from a sequence, and
1588 computing mathematical operations such as intersection, union, difference, and
1589 symmetric difference.
1590 (For other containers see the built in :class:`dict`, :class:`list`,
1591 and :class:`tuple` classes, and the :mod:`collections` module.)
1593 Like other collections, sets support ``x in set``, ``len(set)``, and ``for x in
1594 set``. Being an unordered collection, sets do not record element position or
1595 order of insertion. Accordingly, sets do not support indexing, slicing, or
1596 other sequence-like behavior.
1598 There are currently two builtin set types, :class:`set` and :class:`frozenset`.
1599 The :class:`set` type is mutable --- the contents can be changed using methods
1600 like :meth:`add` and :meth:`remove`. Since it is mutable, it has no hash value
1601 and cannot be used as either a dictionary key or as an element of another set.
1602 The :class:`frozenset` type is immutable and :term:`hashable` --- its contents cannot be
1603 altered after it is created; it can therefore be used as a dictionary key or as
1604 an element of another set.
1606 The constructors for both classes work the same:
1608 .. class:: set([iterable])
1609 frozenset([iterable])
1611 Return a new set or frozenset object whose elements are taken from
1612 *iterable*. The elements of a set must be hashable. To represent sets of
1613 sets, the inner sets must be :class:`frozenset` objects. If *iterable* is
1614 not specified, a new empty set is returned.
1616 Instances of :class:`set` and :class:`frozenset` provide the following
1619 .. describe:: len(s)
1621 Return the cardinality of set *s*.
1623 .. describe:: x in s
1625 Test *x* for membership in *s*.
1627 .. describe:: x not in s
1629 Test *x* for non-membership in *s*.
1631 .. method:: isdisjoint(other)
1633 Return True if the set has no elements in common with *other*. Sets are
1634 disjoint if and only if their intersection is the empty set.
1636 .. method:: issubset(other)
1639 Test whether every element in the set is in *other*.
1641 .. method:: set < other
1643 Test whether the set is a true subset of *other*, that is,
1644 ``set <= other and set != other``.
1646 .. method:: issuperset(other)
1649 Test whether every element in *other* is in the set.
1651 .. method:: set > other
1653 Test whether the set is a true superset of *other*, that is, ``set >=
1654 other and set != other``.
1656 .. method:: union(other, ...)
1659 Return a new set with elements from the set and all others.
1661 .. method:: intersection(other, ...)
1664 Return a new set with elements common to the set and all others.
1666 .. method:: difference(other, ...)
1669 Return a new set with elements in the set that are not in the others.
1671 .. method:: symmetric_difference(other)
1674 Return a new set with elements in either the set or *other* but not both.
1678 Return a new set with a shallow copy of *s*.
1681 Note, the non-operator versions of :meth:`union`, :meth:`intersection`,
1682 :meth:`difference`, and :meth:`symmetric_difference`, :meth:`issubset`, and
1683 :meth:`issuperset` methods will accept any iterable as an argument. In
1684 contrast, their operator based counterparts require their arguments to be
1685 sets. This precludes error-prone constructions like ``set('abc') & 'cbs'``
1686 in favor of the more readable ``set('abc').intersection('cbs')``.
1688 Both :class:`set` and :class:`frozenset` support set to set comparisons. Two
1689 sets are equal if and only if every element of each set is contained in the
1690 other (each is a subset of the other). A set is less than another set if and
1691 only if the first set is a proper subset of the second set (is a subset, but
1692 is not equal). A set is greater than another set if and only if the first set
1693 is a proper superset of the second set (is a superset, but is not equal).
1695 Instances of :class:`set` are compared to instances of :class:`frozenset`
1696 based on their members. For example, ``set('abc') == frozenset('abc')``
1697 returns ``True`` and so does ``set('abc') in set([frozenset('abc')])``.
1699 The subset and equality comparisons do not generalize to a complete ordering
1700 function. For example, any two disjoint sets are not equal and are not
1701 subsets of each other, so *all* of the following return ``False``: ``a<b``,
1702 ``a==b``, or ``a>b``.
1704 Since sets only define partial ordering (subset relationships), the output of
1705 the :meth:`list.sort` method is undefined for lists of sets.
1707 Set elements, like dictionary keys, must be :term:`hashable`.
1709 Binary operations that mix :class:`set` instances with :class:`frozenset`
1710 return the type of the first operand. For example: ``frozenset('ab') |
1711 set('bc')`` returns an instance of :class:`frozenset`.
1713 The following table lists operations available for :class:`set` that do not
1714 apply to immutable instances of :class:`frozenset`:
1716 .. method:: update(other, ...)
1719 Update the set, adding elements from *other*.
1721 .. method:: intersection_update(other, ...)
1724 Update the set, keeping only elements found in it and *other*.
1726 .. method:: difference_update(other, ...)
1729 Update the set, removing elements found in others.
1731 .. method:: symmetric_difference_update(other)
1734 Update the set, keeping only elements found in either set, but not in both.
1736 .. method:: add(elem)
1738 Add element *elem* to the set.
1740 .. method:: remove(elem)
1742 Remove element *elem* from the set. Raises :exc:`KeyError` if *elem* is
1743 not contained in the set.
1745 .. method:: discard(elem)
1747 Remove element *elem* from the set if it is present.
1751 Remove and return an arbitrary element from the set. Raises
1752 :exc:`KeyError` if the set is empty.
1756 Remove all elements from the set.
1759 Note, the non-operator versions of the :meth:`update`,
1760 :meth:`intersection_update`, :meth:`difference_update`, and
1761 :meth:`symmetric_difference_update` methods will accept any iterable as an
1764 Note, the *elem* argument to the :meth:`__contains__`, :meth:`remove`, and
1765 :meth:`discard` methods may be a set. To support searching for an equivalent
1766 frozenset, the *elem* set is temporarily mutated during the search and then
1767 restored. During the search, the *elem* set should not be read or mutated
1768 since it does not have a meaningful value.
1773 Mapping Types --- :class:`dict`
1774 ===============================
1779 triple: operations on; mapping; types
1780 triple: operations on; dictionary; type
1784 A :dfn:`mapping` object maps :term:`hashable` values to arbitrary objects.
1785 Mappings are mutable objects. There is currently only one standard mapping
1786 type, the :dfn:`dictionary`. (For other containers see the built in
1787 :class:`list`, :class:`set`, and :class:`tuple` classes, and the
1788 :mod:`collections` module.)
1790 A dictionary's keys are *almost* arbitrary values. Values that are not
1791 :term:`hashable`, that is, values containing lists, dictionaries or other
1792 mutable types (that are compared by value rather than by object identity) may
1793 not be used as keys. Numeric types used for keys obey the normal rules for
1794 numeric comparison: if two numbers compare equal (such as ``1`` and ``1.0``)
1795 then they can be used interchangeably to index the same dictionary entry. (Note
1796 however, that since computers store floating-point numbers as approximations it
1797 is usually unwise to use them as dictionary keys.)
1799 Dictionaries can be created by placing a comma-separated list of ``key: value``
1800 pairs within braces, for example: ``{'jack': 4098, 'sjoerd': 4127}`` or ``{4098:
1801 'jack', 4127: 'sjoerd'}``, or by the :class:`dict` constructor.
1803 .. class:: dict([arg])
1805 Return a new dictionary initialized from an optional positional argument or
1806 from a set of keyword arguments. If no arguments are given, return a new
1807 empty dictionary. If the positional argument *arg* is a mapping object,
1808 return a dictionary mapping the same keys to the same values as does the
1809 mapping object. Otherwise the positional argument must be a sequence, a
1810 container that supports iteration, or an iterator object. The elements of
1811 the argument must each also be of one of those kinds, and each must in turn
1812 contain exactly two objects. The first is used as a key in the new
1813 dictionary, and the second as the key's value. If a given key is seen more
1814 than once, the last value associated with it is retained in the new
1817 If keyword arguments are given, the keywords themselves with their associated
1818 values are added as items to the dictionary. If a key is specified both in
1819 the positional argument and as a keyword argument, the value associated with
1820 the keyword is retained in the dictionary. For example, these all return a
1821 dictionary equal to ``{"one": 2, "two": 3}``:
1823 * ``dict(one=2, two=3)``
1824 * ``dict({'one': 2, 'two': 3})``
1825 * ``dict(zip(('one', 'two'), (2, 3)))``
1826 * ``dict([['two', 3], ['one', 2]])``
1828 The first example only works for keys that are valid Python identifiers; the
1829 others work with any valid keys.
1832 These are the operations that dictionaries support (and therefore, custom
1833 mapping types should support too):
1835 .. describe:: len(d)
1837 Return the number of items in the dictionary *d*.
1839 .. describe:: d[key]
1841 Return the item of *d* with key *key*. Raises a :exc:`KeyError` if *key* is
1844 If a subclass of dict defines a method :meth:`__missing__`, if the key *key*
1845 is not present, the ``d[key]`` operation calls that method with the key *key*
1846 as argument. The ``d[key]`` operation then returns or raises whatever is
1847 returned or raised by the ``__missing__(key)`` call if the key is not
1848 present. No other operations or methods invoke :meth:`__missing__`. If
1849 :meth:`__missing__` is not defined, :exc:`KeyError` is raised.
1850 :meth:`__missing__` must be a method; it cannot be an instance variable. For
1851 an example, see :class:`collections.defaultdict`.
1853 .. describe:: d[key] = value
1855 Set ``d[key]`` to *value*.
1857 .. describe:: del d[key]
1859 Remove ``d[key]`` from *d*. Raises a :exc:`KeyError` if *key* is not in the
1862 .. describe:: key in d
1864 Return ``True`` if *d* has a key *key*, else ``False``.
1866 .. describe:: key not in d
1868 Equivalent to ``not key in d``.
1870 .. describe:: iter(d)
1872 Return an iterator over the keys of the dictionary. This is a shortcut
1873 for :meth:`iterkeys`.
1877 Remove all items from the dictionary.
1881 Return a shallow copy of the dictionary.
1883 .. classmethod:: fromkeys(seq[, value])
1885 Create a new dictionary with keys from *seq* and values set to *value*.
1887 :meth:`fromkeys` is a class method that returns a new dictionary. *value*
1888 defaults to ``None``.
1890 .. method:: get(key[, default])
1892 Return the value for *key* if *key* is in the dictionary, else *default*.
1893 If *default* is not given, it defaults to ``None``, so that this method
1894 never raises a :exc:`KeyError`.
1898 Return a new view of the dictionary's items (``(key, value)`` pairs). See
1899 below for documentation of view objects.
1903 Return a new view of the dictionary's keys. See below for documentation of
1906 .. method:: pop(key[, default])
1908 If *key* is in the dictionary, remove it and return its value, else return
1909 *default*. If *default* is not given and *key* is not in the dictionary,
1910 a :exc:`KeyError` is raised.
1912 .. method:: popitem()
1914 Remove and return an arbitrary ``(key, value)`` pair from the dictionary.
1916 :meth:`popitem` is useful to destructively iterate over a dictionary, as
1917 often used in set algorithms. If the dictionary is empty, calling
1918 :meth:`popitem` raises a :exc:`KeyError`.
1920 .. method:: setdefault(key[, default])
1922 If *key* is in the dictionary, return its value. If not, insert *key*
1923 with a value of *default* and return *default*. *default* defaults to
1926 .. method:: update([other])
1928 Update the dictionary with the key/value pairs from *other*, overwriting
1929 existing keys. Return ``None``.
1931 :meth:`update` accepts either another dictionary object or an iterable of
1932 key/value pairs (as a tuple or other iterable of length two). If keyword
1933 arguments are specified, the dictionary is then is updated with those
1934 key/value pairs: ``d.update(red=1, blue=2)``.
1936 .. method:: values()
1938 Return a new view of the dictionary's values. See below for documentation of
1944 Dictionary view objects
1945 -----------------------
1947 The objects returned by :meth:`dict.keys`, :meth:`dict.values` and
1948 :meth:`dict.items` are *view objects*. They provide a dynamic view on the
1949 dictionary's entries, which means that when the dictionary changes, the view
1950 reflects these changes.
1952 Dictionary views can be iterated over to yield their respective data, and
1953 support membership tests:
1955 .. describe:: len(dictview)
1957 Return the number of entries in the dictionary.
1959 .. describe:: iter(dictview)
1961 Return an iterator over the keys, values or items (represented as tuples of
1962 ``(key, value)``) in the dictionary.
1964 Keys and values are iterated over in an arbitrary order which is non-random,
1965 varies across Python implementations, and depends on the dictionary's history
1966 of insertions and deletions. If keys, values and items views are iterated
1967 over with no intervening modifications to the dictionary, the order of items
1968 will directly correspond. This allows the creation of ``(value, key)`` pairs
1969 using :func:`zip`: ``pairs = zip(d.values(), d.keys())``. Another way to
1970 create the same list is ``pairs = [(v, k) for (k, v) in d.items()]``.
1972 Iterating views while adding or deleting entries in the dictionary may raise
1973 a :exc:`RuntimeError` or fail to iterate over all entries.
1975 .. describe:: x in dictview
1977 Return ``True`` if *x* is in the underlying dictionary's keys, values or
1978 items (in the latter case, *x* should be a ``(key, value)`` tuple).
1981 Keys views are set-like since their entries are unique and hashable. If all
1982 values are hashable, so that (key, value) pairs are unique and hashable, then
1983 the items view is also set-like. (Values views are not treated as set-like
1984 since the entries are generally not unique.) Then these set operations are
1985 available ("other" refers either to another view or a set):
1987 .. describe:: dictview & other
1989 Return the intersection of the dictview and the other object as a new set.
1991 .. describe:: dictview | other
1993 Return the union of the dictview and the other object as a new set.
1995 .. describe:: dictview - other
1997 Return the difference between the dictview and the other object (all elements
1998 in *dictview* that aren't in *other*) as a new set.
2000 .. describe:: dictview ^ other
2002 Return the symmetric difference (all elements either in *dictview* or
2003 *other*, but not in both) of the dictview and the other object as a new set.
2006 An example of dictionary view usage::
2008 >>> dishes = {'eggs': 2, 'sausage': 1, 'bacon': 1, 'spam': 500}
2009 >>> keys = dishes.keys()
2010 >>> values = dishes.values()
2014 >>> for val in values:
2019 >>> # keys and values are iterated over in the same order
2021 ['eggs', 'bacon', 'sausage', 'spam']
2025 >>> # view objects are dynamic and reflect dict changes
2026 >>> del dishes['eggs']
2027 >>> del dishes['sausage']
2031 >>> # set operations
2032 >>> keys & {'eggs', 'bacon', 'salad'}
2036 .. _bltin-file-objects:
2047 .. XXX this is quite out of date, must be updated with "io" module
2049 File objects are implemented using C's ``stdio`` package and can be
2050 created with the built-in :func:`open` function. File
2051 objects are also returned by some other built-in functions and methods,
2052 such as :func:`os.popen` and :func:`os.fdopen` and the :meth:`makefile`
2053 method of socket objects. Temporary files can be created using the
2054 :mod:`tempfile` module, and high-level file operations such as copying,
2055 moving, and deleting files and directories can be achieved with the
2056 :mod:`shutil` module.
2058 When a file operation fails for an I/O-related reason, the exception
2059 :exc:`IOError` is raised. This includes situations where the operation is not
2060 defined for some reason, like :meth:`seek` on a tty device or writing a file
2063 Files have the following methods:
2066 .. method:: file.close()
2068 Close the file. A closed file cannot be read or written any more. Any operation
2069 which requires that the file be open will raise a :exc:`ValueError` after the
2070 file has been closed. Calling :meth:`close` more than once is allowed.
2072 You can avoid having to call this method explicitly if you use
2073 the :keyword:`with` statement. For example, the following code will
2074 automatically close *f* when the :keyword:`with` block is exited::
2076 from __future__ import with_statement # This isn't required in Python 2.6
2078 with open("hello.txt") as f:
2082 In older versions of Python, you would have needed to do this to get the same
2085 f = open("hello.txt")
2094 Not all "file-like" types in Python support use as a context manager for the
2095 :keyword:`with` statement. If your code is intended to work with any file-like
2096 object, you can use the function :func:`contextlib.closing` instead of using
2097 the object directly.
2100 .. method:: file.flush()
2102 Flush the internal buffer, like ``stdio``'s :cfunc:`fflush`. This may be a
2103 no-op on some file-like objects.
2107 :meth:`flush` does not necessarily write the file's data to disk. Use
2108 :meth:`flush` followed by :func:`os.fsync` to ensure this behavior.
2111 .. method:: file.fileno()
2114 pair: file; descriptor
2117 Return the integer "file descriptor" that is used by the underlying
2118 implementation to request I/O operations from the operating system. This can be
2119 useful for other, lower level interfaces that use file descriptors, such as the
2120 :mod:`fcntl` module or :func:`os.read` and friends.
2124 File-like objects which do not have a real file descriptor should *not* provide
2128 .. method:: file.isatty()
2130 Return ``True`` if the file is connected to a tty(-like) device, else ``False``.
2134 If a file-like object is not associated with a real file, this method should
2135 *not* be implemented.
2138 .. method:: file.__next__()
2140 A file object is its own iterator, for example ``iter(f)`` returns *f* (unless
2141 *f* is closed). When a file is used as an iterator, typically in a
2142 :keyword:`for` loop (for example, ``for line in f: print(line)``), the
2143 :meth:`__next__` method is called repeatedly. This method returns the next
2144 input line, or raises :exc:`StopIteration` when EOF is hit when the file is open
2145 for reading (behavior is undefined when the file is open for writing). In order
2146 to make a :keyword:`for` loop the most efficient way of looping over the lines
2147 of a file (a very common operation), the :meth:`__next__` method uses a hidden
2148 read-ahead buffer. As a consequence of using a read-ahead buffer, combining
2149 :meth:`__next__` with other file methods (like :meth:`readline`) does not work
2150 right. However, using :meth:`seek` to reposition the file to an absolute
2151 position will flush the read-ahead buffer.
2154 .. method:: file.read([size])
2156 Read at most *size* bytes from the file (less if the read hits EOF before
2157 obtaining *size* bytes). If the *size* argument is negative or omitted, read
2158 all data until EOF is reached. The bytes are returned as a string object. An
2159 empty string is returned when EOF is encountered immediately. (For certain
2160 files, like ttys, it makes sense to continue reading after an EOF is hit.) Note
2161 that this method may call the underlying C function :cfunc:`fread` more than
2162 once in an effort to acquire as close to *size* bytes as possible. Also note
2163 that when in non-blocking mode, less data than was requested may be
2164 returned, even if no *size* parameter was given.
2167 .. method:: file.readline([size])
2169 Read one entire line from the file. A trailing newline character is kept in the
2170 string (but may be absent when a file ends with an incomplete line). [#]_ If
2171 the *size* argument is present and non-negative, it is a maximum byte count
2172 (including the trailing newline) and an incomplete line may be returned. An
2173 empty string is returned *only* when EOF is encountered immediately.
2177 Unlike ``stdio``'s :cfunc:`fgets`, the returned string contains null characters
2178 (``'\0'``) if they occurred in the input.
2181 .. method:: file.readlines([sizehint])
2183 Read until EOF using :meth:`readline` and return a list containing the lines
2184 thus read. If the optional *sizehint* argument is present, instead of
2185 reading up to EOF, whole lines totalling approximately *sizehint* bytes
2186 (possibly after rounding up to an internal buffer size) are read. Objects
2187 implementing a file-like interface may choose to ignore *sizehint* if it
2188 cannot be implemented, or cannot be implemented efficiently.
2191 .. method:: file.seek(offset[, whence])
2193 Set the file's current position, like ``stdio``'s :cfunc:`fseek`. The *whence*
2194 argument is optional and defaults to ``os.SEEK_SET`` or ``0`` (absolute file
2195 positioning); other values are ``os.SEEK_CUR`` or ``1`` (seek relative to the
2196 current position) and ``os.SEEK_END`` or ``2`` (seek relative to the file's
2197 end). There is no return value.
2199 For example, ``f.seek(2, os.SEEK_CUR)`` advances the position by two and
2200 ``f.seek(-3, os.SEEK_END)`` sets the position to the third to last.
2202 Note that if the file is opened for appending
2203 (mode ``'a'`` or ``'a+'``), any :meth:`seek` operations will be undone at the
2204 next write. If the file is only opened for writing in append mode (mode
2205 ``'a'``), this method is essentially a no-op, but it remains useful for files
2206 opened in append mode with reading enabled (mode ``'a+'``). If the file is
2207 opened in text mode (without ``'b'``), only offsets returned by :meth:`tell` are
2208 legal. Use of other offsets causes undefined behavior.
2210 Note that not all file objects are seekable.
2213 .. method:: file.tell()
2215 Return the file's current position, like ``stdio``'s :cfunc:`ftell`.
2219 On Windows, :meth:`tell` can return illegal values (after an :cfunc:`fgets`)
2220 when reading files with Unix-style line-endings. Use binary mode (``'rb'``) to
2221 circumvent this problem.
2224 .. method:: file.truncate([size])
2226 Truncate the file's size. If the optional *size* argument is present, the file
2227 is truncated to (at most) that size. The size defaults to the current position.
2228 The current file position is not changed. Note that if a specified size exceeds
2229 the file's current size, the result is platform-dependent: possibilities
2230 include that the file may remain unchanged, increase to the specified size as if
2231 zero-filled, or increase to the specified size with undefined new content.
2232 Availability: Windows, many Unix variants.
2235 .. method:: file.write(str)
2237 Write a string to the file. Due to buffering, the string may not actually
2238 show up in the file until the :meth:`flush` or :meth:`close` method is
2241 The meaning of the return value is not defined for every file-like object.
2242 Some (mostly low-level) file-like objects may return the number of bytes
2243 actually written, others return ``None``.
2246 .. method:: file.writelines(sequence)
2248 Write a sequence of strings to the file. The sequence can be any iterable
2249 object producing strings, typically a list of strings. There is no return value.
2250 (The name is intended to match :meth:`readlines`; :meth:`writelines` does not
2251 add line separators.)
2253 Files support the iterator protocol. Each iteration returns the same result as
2254 ``file.readline()``, and iteration ends when the :meth:`readline` method returns
2257 File objects also offer a number of other interesting attributes. These are not
2258 required for file-like objects, but should be implemented if they make sense for
2259 the particular object.
2262 .. attribute:: file.closed
2264 bool indicating the current state of the file object. This is a read-only
2265 attribute; the :meth:`close` method changes the value. It may not be available
2266 on all file-like objects.
2269 .. XXX does this still apply?
2270 .. attribute:: file.encoding
2272 The encoding that this file uses. When strings are written to a file,
2273 they will be converted to byte strings using this encoding. In addition, when
2274 the file is connected to a terminal, the attribute gives the encoding that the
2275 terminal is likely to use (that information might be incorrect if the user has
2276 misconfigured the terminal). The attribute is read-only and may not be present
2277 on all file-like objects. It may also be ``None``, in which case the file uses
2278 the system default encoding for converting strings.
2281 .. attribute:: file.errors
2283 The Unicode error handler used along with the encoding.
2286 .. attribute:: file.mode
2288 The I/O mode for the file. If the file was created using the :func:`open`
2289 built-in function, this will be the value of the *mode* parameter. This is a
2290 read-only attribute and may not be present on all file-like objects.
2293 .. attribute:: file.name
2295 If the file object was created using :func:`open`, the name of the file.
2296 Otherwise, some string that indicates the source of the file object, of the
2297 form ``<...>``. This is a read-only attribute and may not be present on all
2301 .. attribute:: file.newlines
2303 If Python was built with the :option:`--with-universal-newlines` option to
2304 :program:`configure` (the default) this read-only attribute exists, and for
2305 files opened in universal newline read mode it keeps track of the types of
2306 newlines encountered while reading the file. The values it can take are
2307 ``'\r'``, ``'\n'``, ``'\r\n'``, ``None`` (unknown, no newlines read yet) or a
2308 tuple containing all the newline types seen, to indicate that multiple newline
2309 conventions were encountered. For files not opened in universal newline read
2310 mode the value of this attribute will be ``None``.
2318 :class:`memoryview`\s allow Python code to access the internal data of an object
2319 that supports the buffer protocol without copying. Memory can be interpreted as
2320 simple bytes or complex data structures.
2322 .. class:: memoryview(obj)
2324 Create a :class:`memoryview` that references *obj*. *obj* must support the
2325 buffer protocol. Builtin objects that support the buffer protocol include
2326 :class:`bytes` and :class:`bytearray`.
2328 ``len(view)`` returns the total number of bytes in the memoryview, *view*.
2330 A :class:`memoryview` supports slicing to expose its data. Taking a single
2331 index will return a single byte. Full slicing will result in a subview::
2333 >>> v = memoryview(b'abcefg')
2339 <memory at 0x77ab28>
2343 <memory at 0x744f18>
2346 If the object the memory view is over supports changing its data, the
2347 memoryview supports slice assignment::
2349 >>> data = bytearray(b'abcefg')
2350 >>> v = memoryview(data)
2355 bytearray(b'zbcefg')
2358 bytearray(b'a123fg')
2360 Traceback (most recent call last):
2361 File "<stdin>", line 1, in <module>
2362 ValueError: cannot modify size of memoryview object
2364 Notice how the size of the memoryview object can not be changed.
2367 :class:`memoryview` has two methods:
2369 .. method:: tobytes()
2371 Return the data in the buffer as a bytestring.
2373 .. method:: tolist()
2375 Return the data in the buffer as a list of integers. ::
2377 >>> memoryview(b'abc').tolist()
2380 There are also several readonly attributes available:
2382 .. attribute:: format
2384 A string containing the format (in :mod:`struct` module style) for each
2385 element in the view. This defaults to ``'B'``, a simple bytestring.
2387 .. attribute:: itemsize
2389 The size in bytes of each element of the memoryview.
2391 .. attribute:: shape
2393 A tuple of integers the length of :attr:`ndim` giving the shape of the
2394 memory as a N-dimensional array.
2398 An integer indicating how many dimensions of a multi-dimensional array the
2401 .. attribute:: strides
2403 A tuple of integers the length of :attr:`ndim` giving the size in bytes to
2404 access each element for each dimension of the array.
2406 .. memoryview.suboffsets isn't documented because it only seems useful for C
2409 .. _typecontextmanager:
2411 Context Manager Types
2412 =====================
2415 single: context manager
2416 single: context management protocol
2417 single: protocol; context management
2419 Python's :keyword:`with` statement supports the concept of a runtime context
2420 defined by a context manager. This is implemented using two separate methods
2421 that allow user-defined classes to define a runtime context that is entered
2422 before the statement body is executed and exited when the statement ends.
2424 The :dfn:`context management protocol` consists of a pair of methods that need
2425 to be provided for a context manager object to define a runtime context:
2428 .. method:: contextmanager.__enter__()
2430 Enter the runtime context and return either this object or another object
2431 related to the runtime context. The value returned by this method is bound to
2432 the identifier in the :keyword:`as` clause of :keyword:`with` statements using
2433 this context manager.
2435 An example of a context manager that returns itself is a file object. File
2436 objects return themselves from __enter__() to allow :func:`open` to be used as
2437 the context expression in a :keyword:`with` statement.
2439 An example of a context manager that returns a related object is the one
2440 returned by :func:`decimal.localcontext`. These managers set the active
2441 decimal context to a copy of the original decimal context and then return the
2442 copy. This allows changes to be made to the current decimal context in the body
2443 of the :keyword:`with` statement without affecting code outside the
2444 :keyword:`with` statement.
2447 .. method:: contextmanager.__exit__(exc_type, exc_val, exc_tb)
2449 Exit the runtime context and return a Boolean flag indicating if any exception
2450 that occurred should be suppressed. If an exception occurred while executing the
2451 body of the :keyword:`with` statement, the arguments contain the exception type,
2452 value and traceback information. Otherwise, all three arguments are ``None``.
2454 Returning a true value from this method will cause the :keyword:`with` statement
2455 to suppress the exception and continue execution with the statement immediately
2456 following the :keyword:`with` statement. Otherwise the exception continues
2457 propagating after this method has finished executing. Exceptions that occur
2458 during execution of this method will replace any exception that occurred in the
2459 body of the :keyword:`with` statement.
2461 The exception passed in should never be reraised explicitly - instead, this
2462 method should return a false value to indicate that the method completed
2463 successfully and does not want to suppress the raised exception. This allows
2464 context management code (such as ``contextlib.nested``) to easily detect whether
2465 or not an :meth:`__exit__` method has actually failed.
2467 Python defines several context managers to support easy thread synchronisation,
2468 prompt closure of files or other objects, and simpler manipulation of the active
2469 decimal arithmetic context. The specific types are not treated specially beyond
2470 their implementation of the context management protocol. See the
2471 :mod:`contextlib` module for some examples.
2473 Python's :term:`generator`\s and the ``contextlib.contextfactory`` :term:`decorator`
2474 provide a convenient way to implement these protocols. If a generator function is
2475 decorated with the ``contextlib.contextfactory`` decorator, it will return a
2476 context manager implementing the necessary :meth:`__enter__` and
2477 :meth:`__exit__` methods, rather than the iterator produced by an undecorated
2480 Note that there is no specific slot for any of these methods in the type
2481 structure for Python objects in the Python/C API. Extension types wanting to
2482 define these methods must provide them as a normal Python accessible method.
2483 Compared to the overhead of setting up the runtime context, the overhead of a
2484 single class dictionary lookup is negligible.
2489 Other Built-in Types
2490 ====================
2492 The interpreter supports several other kinds of objects. Most of these support
2493 only one or two operations.
2501 The only special operation on a module is attribute access: ``m.name``, where
2502 *m* is a module and *name* accesses a name defined in *m*'s symbol table.
2503 Module attributes can be assigned to. (Note that the :keyword:`import`
2504 statement is not, strictly speaking, an operation on a module object; ``import
2505 foo`` does not require a module object named *foo* to exist, rather it requires
2506 an (external) *definition* for a module named *foo* somewhere.)
2508 A special member of every module is :attr:`__dict__`. This is the dictionary
2509 containing the module's symbol table. Modifying this dictionary will actually
2510 change the module's symbol table, but direct assignment to the :attr:`__dict__`
2511 attribute is not possible (you can write ``m.__dict__['a'] = 1``, which defines
2512 ``m.a`` to be ``1``, but you can't write ``m.__dict__ = {}``). Modifying
2513 :attr:`__dict__` directly is not recommended.
2515 Modules built into the interpreter are written like this: ``<module 'sys'
2516 (built-in)>``. If loaded from a file, they are written as ``<module 'os' from
2517 '/usr/local/lib/pythonX.Y/os.pyc'>``.
2522 Classes and Class Instances
2523 ---------------------------
2525 See :ref:`objects` and :ref:`class` for these.
2533 Function objects are created by function definitions. The only operation on a
2534 function object is to call it: ``func(argument-list)``.
2536 There are really two flavors of function objects: built-in functions and
2537 user-defined functions. Both support the same operation (to call the function),
2538 but the implementation is different, hence the different object types.
2540 See :ref:`function` for more information.
2548 .. index:: object: method
2550 Methods are functions that are called using the attribute notation. There are
2551 two flavors: built-in methods (such as :meth:`append` on lists) and class
2552 instance methods. Built-in methods are described with the types that support
2555 If you access a method (a function defined in a class namespace) through an
2556 instance, you get a special object: a :dfn:`bound method` (also called
2557 :dfn:`instance method`) object. When called, it will add the ``self`` argument
2558 to the argument list. Bound methods have two special read-only attributes:
2559 ``m.__self__`` is the object on which the method operates, and ``m.__func__`` is
2560 the function implementing the method. Calling ``m(arg-1, arg-2, ..., arg-n)``
2561 is completely equivalent to calling ``m.__func__(m.__self__, arg-1, arg-2, ...,
2564 Like function objects, bound method objects support getting arbitrary
2565 attributes. However, since method attributes are actually stored on the
2566 underlying function object (``meth.__func__``), setting method attributes on
2567 bound methods is disallowed. Attempting to set a method attribute results in a
2568 :exc:`TypeError` being raised. In order to set a method attribute, you need to
2569 explicitly set it on the underlying function object::
2576 c.method.__func__.whoami = 'my name is c'
2578 See :ref:`types` for more information.
2581 .. _bltin-code-objects:
2586 .. index:: object: code
2590 single: __code__ (function object attribute)
2592 Code objects are used by the implementation to represent "pseudo-compiled"
2593 executable Python code such as a function body. They differ from function
2594 objects because they don't contain a reference to their global execution
2595 environment. Code objects are returned by the built-in :func:`compile` function
2596 and can be extracted from function objects through their :attr:`__code__`
2597 attribute. See also the :mod:`code` module.
2603 A code object can be executed or evaluated by passing it (instead of a source
2604 string) to the :func:`exec` or :func:`eval` built-in functions.
2606 See :ref:`types` for more information.
2609 .. _bltin-type-objects:
2618 Type objects represent the various object types. An object's type is accessed
2619 by the built-in function :func:`type`. There are no special operations on
2620 types. The standard module :mod:`types` defines names for all standard built-in
2623 Types are written like this: ``<class 'int'>``.
2626 .. _bltin-null-object:
2631 This object is returned by functions that don't explicitly return a value. It
2632 supports no special operations. There is exactly one null object, named
2633 ``None`` (a built-in name).
2635 It is written as ``None``.
2638 .. _bltin-ellipsis-object:
2643 This object is commonly used by slicing (see :ref:`slicings`). It supports no
2644 special operations. There is exactly one ellipsis object, named
2645 :const:`Ellipsis` (a built-in name).
2647 It is written as ``Ellipsis`` or ``...``.
2653 Boolean values are the two constant objects ``False`` and ``True``. They are
2654 used to represent truth values (although other values can also be considered
2655 false or true). In numeric contexts (for example when used as the argument to
2656 an arithmetic operator), they behave like the integers 0 and 1, respectively.
2657 The built-in function :func:`bool` can be used to cast any value to a Boolean,
2658 if the value can be interpreted as a truth value (see section Truth Value
2664 pair: Boolean; values
2666 They are written as ``False`` and ``True``, respectively.
2674 See :ref:`types` for this information. It describes stack frame objects,
2675 traceback objects, and slice objects.
2683 The implementation adds a few special read-only attributes to several object
2684 types, where they are relevant. Some of these are not reported by the
2685 :func:`dir` built-in function.
2688 .. attribute:: object.__dict__
2690 A dictionary or other mapping object used to store an object's (writable)
2694 .. attribute:: instance.__class__
2696 The class to which a class instance belongs.
2699 .. attribute:: class.__bases__
2701 The tuple of base classes of a class object. If there are no base classes, this
2702 will be an empty tuple.
2705 .. attribute:: class.__name__
2707 The name of the class or type.
2710 The following attributes are only supported by :term:`new-style class`\ es.
2712 .. attribute:: class.__mro__
2714 This attribute is a tuple of classes that are considered when looking for
2715 base classes during method resolution.
2718 .. method:: class.mro()
2720 This method can be overridden by a metaclass to customize the method
2721 resolution order for its instances. It is called at class instantiation, and
2722 its result is stored in :attr:`__mro__`.
2725 .. method:: class.__subclasses__
2727 Each new-style class keeps a list of weak references to its immediate
2728 subclasses. This method returns a list of all those references still alive.
2731 >>> int.__subclasses__()
2735 .. rubric:: Footnotes
2737 .. [#] Additional information on these special methods may be found in the Python
2738 Reference Manual (:ref:`customization`).
2740 .. [#] As a consequence, the list ``[1, 2]`` is considered equal to ``[1.0, 2.0]``, and
2741 similarly for tuples.
2743 .. [#] They must have since the parser can't tell the type of the operands.
2745 .. [#] To format only a tuple you should therefore provide a singleton tuple whose only
2746 element is the tuple to be formatted.
2748 .. [#] The advantage of leaving the newline on is that returning an empty string is
2749 then an unambiguous EOF indication. It is also possible (in cases where it
2750 might matter, for example, if you want to make an exact copy of a file while
2751 scanning its lines) to tell whether the last line of a file ended in a newline
2752 or not (yes this happens!).